Defer parsing of JavaScript – targeting .js file

Question

I am hooking Varvy’s script before my closing </body> tag to defer parsing of JS, but it does not seem to be working – scanning the site with GTMetrix before and after gives the same result. What is wrong – could it be an incompatibility with the theme? am I just not using the correct path to the .js file? Is the script itself not working?

My code in functions.php of child theme:

/**
Defer parsing of JavaScript with code snippet from Varvy
*/

add_action( 'wp_footer', 'my_footer_scripts', 999 );

function my_footer_scripts(){
    ?>
    <script type="text/javascript">
        function downloadJSAtOnload() {
        var element = document.createElement("script");
        element.src = "path/to/script.js";
        document.body.appendChild(element);
        }
        if (window.addEventListener)
        window.addEventListener("load", downloadJSAtOnload, false);
        else if (window.attachEvent)
        window.attachEvent("onload", downloadJSAtOnload);
        else window.onload = downloadJSAtOnload;
    </script>
    <?php
}

How shall I provide the script path?

  • absolute as https://www.mysite.it/wp-content/cache/wpo-minify/1600790958/assets/wpo-minify-footer-62866f70.min.js
  • absolute as /www.mysite.it/wp-content/cache/wpo-minify/1600790958/assets/wpo-minify-footer-62866f70.min.js
  • relative to footer.php, that would be ../../cache/wpo-minify/1600790958/assets/wpo-minify-footer-62866f70.min.js

since my directories structure is

.
└── www.mysite.it
    └── wp-content
        ├── cache
        │   └── wpo-minify
        │       └── 1600790958
        │           └── assets
        │               └── wpo-minify-footer-62866f70.min.js
        └── themes
            ├── bridge
            │   └── footer.php
            └── bridge-child
                └── functions.php
0
DavideL 4 months 0 Answers 22 views 0

Leave an answer