Eliminate render blocking javascript and defer parsing of js

Why is it important to Eliminate render blocking javascriptYou know your website needs to be fast. Even if the users with slow Internet connection don’t matter much to you, you should consider the speed optimization of your website because it affects your search engine rankings and these rankings obviously reflect on your site’s traffic. One of the common hindrance in improving site speed is to Eliminate render blocking javascript.

Render blocking javascript is the script that is fetched and parsed before the contents of your page are displayed. Until these scripts are downloaded, the visitors sees a blank page. A better alternative to this is to load contents first, then the related javascript files so that the visitor’s wait time could be reduced.

To eliminate render blocking javascript and defer parsing of javascript

  1. Place all the javascript files just before the closing </body> tag.
  2. Set “defer” attribute to true.

But even after using these methods you get a warning from GTmetrix and Pagespeed. To get past these warnings, use following method.

function loadJsFiles()
{
    //create an array of javascript file paths
    var jsFiles = [
        '//path/to/script-1.js',
        '//path/to/script-2.js',
    ];

    //loop through the array to create script element and set the "src" attribute to the script path.
    for (x in jsFiles){
        var element = document.createElement("script");
        element.src = jsFiles[x];
        document.body.appendChild(element);
    }
}

 

Next, call this function on window load event

window.addEventListener("load", loadJsFiles, false);

 

The above method will not only truly load the js files after the content is loaded, it will also remove the warnings like “Defer parsing of javascript” and “Eliminate render blocking javascript above content fold”.

Leave a Reply

Your email address will not be published. Required fields are marked *