How to fix defer parsing of JavaScript in your website or WordPress?

Many have encountered “defer parsing of JavaScript” problem. It is a page speed issue found in GTMetrixGoogle PageSpeed Insights and in any other page analyzer. The average score is 55%, where we can conclude it is not easy to fix it. Moreover, it is an important step for page speed. How can you effectively fix it? How to add it properly in WordPress??

What is defer parsing of JavaScript? By deferring parsing of unneeded JavaScript until page needs to be executed, you can reduce the initial load time of it. You have 2 options – asynchronous or defer method.

Async

If you write effectively your JavaScript, you should add async to 90% of the scripts. With an asynchronous script the browser can continue parsing and rendering HTML that comes after the async script. The browser does not need to wait for the script to complete. It is fetched as soon as possible, but its execution is deferred until the browser’s User Interface thread is not busy.

<script async src="siteScript.js" onload="myInit()"><script>

Defer

To defer method, you must identify all the JavaScript functions that are not actually used by the document before the onload event. For any file containing more than 25 uncalled functions, move all those functions to a separate, external JS file. You may need some refactoring of your code to work around dependencies between files.

<script defer src="siteScript.js" onload="myInit()"><script>

WordPress import

Plugins & Theme Async/Defer Parsing of JavaScript

Paste the code below in the your functions.php (child’s theme).

//Defer Pasing JavaScript for entire website, including Plugins, but without jQuery.js
//Feel free to change "async" to "defer". $files will be excluded
function defer_parsing_of_js($url)
{
//Specify which files to EXCLUDE from defer method. Always add jquery.js
    $files = array('jquery.js');
//let's not break back-end
    if (!is_admin()) {
        if (false === strpos($url, '.js')) {
            return $url;
        }

        foreach ($files as $file) {
            if (strpos($url, $file)) {
                return $url;
            }
        }
    } else {
        return $url;
    }
    return "$url' async='async";

}
add_filter('clean_url', 'defer_parsing_of_js', 11, 1);

If you want to use defer just replace async=’async’ with defer=’defer’.

Deferred – delays the execution of the script until the HTML parser has finished.
Asynchronous – executes when the script is ready and doesn’t disrupt HTML parsing.

Difference between async and defer

The difference between async and defer centers around when the script is executed. Each async script executes at the first opportunity after it is finished downloading and before the window’s load event. This means it is possible that async scripts are not executed in the order in which they occur in the page. In the past, async lacked of support in older browsers.

In contrast, the defer scripts are guaranteed to be executed in the order they occur in the page. That execution starts after parsing is completely finished, but before the document’s DOMContentLoaded event. WebKit-based browsers, Firefox has long supported the defer and onload attributes and support for async was added in version 3.6. Internet Explorer has also long supported the defer attribute.

Conclusion

Which one is better? I will go for async for sure! Since WebKit had implemented async will speed up the websites a lot.

What do you think?

9 comments on “How to fix defer parsing of JavaScript in your website or WordPress?

  • Balaji

    I have added this code in function.php in my wordpress website. I am Avada theme.
    It’s not working. Still it shows render blocking issue.

    Reply
    • Hello,

      You can use the first snippet (Plugins & Theme Async/Defer Parsing of JavaScript) in your child themes functions.php file.

      Reply
  • Thanks for the Tutorial Alexander.

    I have added the code in my themes functions.php folder. However, our sites menu has disappeared and the custom grids that we implemented with Visual Composer.

    Any suggestions on how we can overcome this?

    Thanks in advanced

    Reply
        • Hi Ryan,

          Please check the difference between async and defer. If you care about your score in GTMetrix or Google PageSpeed Insights, “defer” method is much safer.

          About ASYNC – “This means it is possible that async scripts are not executed in the order in which they occur in the page” from the article above. In general async is better if you do not run into any issues.

          Reply
  • I think async is the best solution for this problem. But how about defer parsing of inline Javascript? Thank you very much if you reply…

    Reply
    • Hi Bang,

      This is a terrible way to execute JS. Always try to add it in a file or use plugins like Autoptimize to combine all JS files into one single file. Also, do not forget to place your JS in footer, before closing tag.

      Reply
  • I think script_loader_tag filter is a better candidate for such optimizations.

    Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.