How to Defer Parsing of JavaScript Properly + WordPress Fix [Updated Guide]

Updated on

Learn how to Defer Parsing of JavaScript to improve pagespeed score. And how you can fix ‘Eliminate render-blocking of JavaScript’ warning in Google PageSpeed Insights by deferring non-critical JavaScript(s). The newer version of Google PageSpeed Insight refers to this issue as ‘Eliminate render-blocking resources’; these render-blocking resources may include JavaScripts and CSS.

In this article, I will cover what is defer parsing of JavaScript, how to defer parsing of JavaScript properly, why you should defer parsing JavaScript, how to find render-blocking JavaScript(s) which are to be deferred, how to defer multiple JavaScripts in one go, how you can defer parsing of JavaScript in WordPress with or without plugin and how does defer loading of JavaScript help to speed up your website?

how to defer parsing of javascript in wordpress - how to defer parsing javascript
How to Defer Parsing of JavaScript

In a nutshell, we’ll eliminate render-blocking JavaScript(s) not by actually removing (deleting) them from the website code but by defer loading them. So that they stop blocking the loading (rendering) of meaningful content (the first paint) of the website.

These terms (the above terminology) might be overwhelming for you at first, especially if you’re not a tech guy.

But, don’t worry about that!

I am going to explain everything step by step in simple words. So that you can proceed at your pace and implement the methods to fix ‘Eliminate render-blocking resources’ on your website/blog.

What is Defer Parsing JavaScript

A web page is made of up several components which include HTML, CSS/Stylesheets, JavaScript, and graphical (images & icons) components, etc. These components are stacked one over another in the code structure of the web page.

When a user types your website URL in the web browser’s address bar and hit enter. The browser first establishes the connection with the server on which your website is hosted.

Once the connection is established, the browser starts rendering the components of the webpage to display the web page.

The browser renders the components serially from the top toward the bottom of the webpage. That means what comes first rendered first and so on.

When the browser encounters JavaScript on a web page, it downloads the JavaScript, executes it, and then proceeds to render the next component. So during this time browser stops rendering the rest of the web page.

Every time the browser encounters JavaScript, it stops rendering the rest of the webpage until it renders and executes the encountered JavaScript.

That’s how JavaScript blocks the critical rendering path.

To avoid this situation, Google Engineers recommend deferring non-critical JavaScript.

The question still remains the same, What is Defer Parsing of JavaScript?

Defer Parsing of JavaScript can be defined as the process of using defer or async attribute with JavaScript to avoid render blocking of the first paint of a web page. These attributes tell the web browser to parse and execute the JavaScript in parallel (asynchronously) or after (defer) the parsing of HTML of a web page. Thus, the visitors need not wait longer to see the meaningful content of the web page.

Difference between defer and async

Now you know that there are two attributes – defer and async; that can be used to defer javascript loading.

Before we talk about the difference between defer and async, let’s see how does <script> tag works.

Legend

Legend - async vs defer attribute
legend async vs defer attribute

<script>

script tag
script tag

When we use <script> tag to add script in our code, the HTML is keep parsing till the script file is reached, then onwards parsing will be paused until the script file is downloaded and executed.

Suitability: Not recommended in most cases.

<script defer>

script defer attribute
script defer attribute

When defer attribute is appended with a script tag, the script file is downloaded alongside the HTML parsing but the downloaded script executes only after the completion of HTML parsing.

Suitability: For non-critical script files.

<script async>

script async attribute
script async attribute

When async attributed is used with the script tag, the script file downloads during HTML parsing, then HTML parsing pauses just to execute the downloaded-script file.

Suitability: For critical script files that cannot be inline.  

Defer loading of JS & PageSpeed Insights recommendation

Let’s try to put this in a perspective with Google PageSpeed Insights warning and recommendation.

When you test, a website using Google Pagespeed Insights Tool, you get some warnings and recommendations to fix those warnings/errors.

Google PSI - Render blocking resources - JavaScripts to be deferred
Google PSI – Render blocking resources – JavaScripts to be deferred

The PageSpeed Insights (PSI) text for render-blocking resources says,

Eliminate render-blocking resources.

Resources are blocking the first paint of your page. Consider delivering critical JS/CSS inline and deferring all non-critical JS/styles.

This warning triggers for two different elements i.e. JavaScript (JS) and CSS when any of them block the critical rendering path 1 during the website loading. Here in this article, we are discussing the JavaScript part.

(In the previous version of PageSpeed Insights Tool, the same warning (for the JavaScript) used to be called ‘Eliminate render-blocking of JavaScript’.)

In simple words, this warning triggers when there are some JavaScript(s) loading on your website which blocks the loading of the content that matters most to your visitors.

This means your visitors have to wait longer to see the meaningful content of your website because JavaScript(s) are blocking the rendering of content.

Clearly, Pagespeed Insights or other site speed testing tools (GTMetrix, etc.) show this warning/error, if your site loads some JavaScript(s) that block the loading of meaningful content (the first paint) of your site.

And this needs to be fixed.

Critical vs Non-critical JavaScript: Explained

As Google PageSpeed Insights (PSI) recommendation says you should deliver critical JS inline and defer all non-critical JS.

What does this mean?

Let’s break that down by terminology.

Critical JavaScripts: JavaScripts that are necessary to load during optimized critical rendering.

Non-critical JavaScripts: Those JS that can wait to load until the first meaningful content (the first paint) of the webpage has loaded.

Inline Delivery: Inline delivery refers to loading a resource (in this case JS) within the HTML code instead of calling/importing that separately.

Curious? Why does JavaScript block the critical rendering path in the first place?

We’ll discuss that in the next section with other reasons why you should Defer JavaScript Parsing.

Do you know? how to

Why You Should Defer Parsing of JavaScript

JavaScript Execution: is a Heavier Task

How does JS Affect SiteSpeed?

First of all, JavaScript(s) is one of the major culprits to make your website slow.

Wondering, why is that?

Because when the web browser comes across a script, it executes the script first before continuing to load HTML that includes the content users are looking for.

For a browser, executing JavaScript is a heavier task (depending on the size of the script) and takes more time as compared to rendering the meaningful content (the first paint) of the webpage.

Hence JavaScript affects the critical rendering path and slows down pagespeed of your website.

Why not defer this heavier task of JS execution so that the critical rendering path remains uninterrupted, right?

Pagespeed: is now a Ranking Factor

Site speed has already become a ranking signal.

About a decade ago Google announced 2 in an official blog post on Google Webmaster Central Blog that site speed has become a ranking signal.

In another blog post published on the Official Webmaster Central Blog in 2018, they revealed 3 that Google started using page speed as a ranking factor in mobile search ranking.

Since Google had declared pagespeed a factor in search result rankings for desktop and mobile. Therefore, site speed optimization has become a significant aspect of technical SEO.

For the same reason, Google PageSpeed Insights Tool recommends deferred parsing of JavaScript as one of the solutions 4 to remove render-blocking JavaScript in above-the-fold content.

User Experience: decides Your Site’s Success

How does JavaScript affect user experience (UX)?

We have already discussed that JavaScript(s) slow down the pagespeed by blocking the rendering of the first paint (the meaningful content). That led to more loading time and a longer wait for users to see the content; bad user experience, right?

Speed matters a lot, the truth is users do not like slow-loading websites. In fact, studies show that users leave a slow-loading site early and move on.

On the contrary, you want your website audience to engage with your site and eventually turn into a customer, subscriber, or ad-viewer. In order to make that happen, you need to improve your pagespeed by deferring non-critical JavaScript(s).

Reasons to Defer Loading of JavaScript: Summing it up

As I mentioned above, however, the parser (browser) starts downloading and executing the script over parsing the rest of HTML, whenever it encounters the script.

But the fact is, most of the JavaScript(s) come into use when the complete web page is loaded. For example, in some animation, effects, functionality, etc.

Therefore, it is a good idea to load JavaScript(s) only after the content has loaded.

This way deferred loading of JavaScript does not affect the critical render path and consequently helps to speed up your website. And hence, a better user experience for your readers.

The statistics show that by making your site load faster, you can improve your search ranking on desktop as well as mobile.

You’re writing FAQs for a landing page for a Web Development Company.

And in the answer to a question you mentioned an exact figure for the price of the development service.

Q: Do you offer eCommerce Website Development?

A: Yes, we offer a feature-rich eCommerce website development for only $10,000. Check our portfolio for delivered projects.

The problem here is that the user may go away by seeing the price which is higher than his budget. He made his decision by seeing the price ONLY.

However, there might be chances that he may raise his budget by seeing the quality of the website delivered (portfolio) by the company. Or by the customer-satisfaction level of the company’s clients or any factor which can change his mind while browsing the company’s website.

So you should write your answer in such a way that convinces the user to click your link.

A better version of that FAQ could be,

Q: Do you offer eCommerce Website Development?

A: Yes, we offer feature-rich eCommerce website development at a reasonable price. Please check our portfolio for delivered eCommerce projects. And don’t forget to read testimonials for customer satisfaction.

Now, since you have an understanding of what is defer parsing of JavaScript and why you should defer loading of JavaScript(s).

It is a good time to figure out which JavaScript(s) (on your website) are the culprits and need to be deferred.

If you already know which JavaScript(s) on your website are blocking the critical rendering path, you may skip the following section and jump to the implementation part. Otherwise, keep on reading…

How to Find Render-blocking JavaScript(s)

JavaScript(s) which block the rendering of meaningful content are called ‘Render Blocking JavaScript(s)’ and need to be deferred.

You can find render-blocking JavaScript(s) by analyzing your website using site speed testing tools.

There are several pagespeed testing tools available to analyze a website for site speed and loading time. I am sharing with you the most reliable and trusted tools for pagespeed testing.

Test your site using these tools and note the results of these tools so that you can compare the results before and after implementing defer parsing of JavaScript(s).

1. PageSpeed Insights by Google

PageSpeed Insights by Google
PageSpeed Insights by Google

Google PageSpeed Insights (PSI) is an exclusive pagespeed testing tool by Google. Test your website using Google PSI Tool to find out render-blocking JavaScript(s). PageSpeed Insights Tool results give information about warnings and their solutions/fixes.

2. GTmetrix

GTmetrix - Speed and Performance Test Tool
GTmetrix – Speed and Performance Test Tool

This one (GTmetrix) is another good free tool to test site speed. You can test your site with GTmetrix to know which JavaScripts need to be deferred.

3. Pingdom Tools

Pingdom Tools for Website Speed Test
Pingdom Tools for Website Speed Test

Solarwinds’ Pingdom Tools are also very popular when it comes to site speed testing tools. You can test your site using Pingdom Tools to check the number of JS requests on your site and how much they contribute to the total number of requests.

Now you know which JavaScript(s) are making your site slow and need to be deferred. So, let’s see how to fix this issue by deferring non-critical JavaScript(JS).

Test Results: Before Defer Parsing of JavaScript

I have tested a website before implementing defer parsing of JavaScript. Consider these a baseline and compare these results after deferred loading of JavaScripts.

Pagespeed Insights Result before Defer Parsing of JS
Pagespeed Insights Result before Defer Parsing of JS
GTmetrix Result before Defer Parsing of JS
GTmetrix Result before Defer Parsing of JS

How to Defer Parsing of JavaScript [Step by step]

You need to use the following code to defer parsing JavaScript. Insert this code in HTML file just before the </body> tag. Read the instructions given below to use this script.

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

Instructions for Defer Parsing JavaScript using the script

Don’t forget to take a complete backup before making any changes in the code. If something went wrong, you can use that backup to go back.

  1. Copy the code and paste it in HTML file just before the </body> tag (near the bottom of HTML file).
  2. Replace script_to_be_deferred.js with the link of the JavaScript which is to be deferred. You can copy the link of JavaScript(s) (which Google PageSpeed tool suggests to defer) from Google PageSpeed Insights tool results for your website.
  3. Save changes. And you are done.
  4. Finally, test your website again to see the effect.

Code to Defer Multiple JavaScripts in One-go

If you want to defer multiple scripts in one go. You can use the same script with little modification. In the following code replace defer1.js, defer3.js, and defer3.js, etc. with the link of scripts that you want to defer.

 < script type="text/javascript">
function parseJSAtOnload() {
var links = ["defer1.js", "defer2.js", "defer3.js"],
headElement = document.getElementsByTagName("head")[0],
linkElement, i;
for (i = 0; i < links.length; i++) {
linkElement = document.createElement("script");
linkElement.src = links[i];
headElement.appendChild(linkElement);
}
}
if (window.addEventListener)
window.addEventListener("load", parseJSAtOnload, false);
else if (window.attachEvent)
window.attachEvent("onload", parseJSAtOnload);
else window.onload = parseJSAtOnload;
</script >  

How to Defer Parsing of JavaScript in WordPress

You can defer parsing of JavaScript in WordPress by following methods:

  1. Using WordPress Plugins (with a plugin) – suitable for all plugin lovers.
  2. Adding a Code Snippet to function.php file – suitable for those who are used to playing with code and editing files in WordPress. – without plugin method #1
  3. Using the Script mentioned above  – suitable for geeks who don’t want to use a plugin. – without plugin method #2

1. Defer Parsing of JavaScript using WordPress Plugin

There are several WordPress plugins available to defer parsing of JavaScript in WordPress, I am listing the best plugins that stand out in the crowd because of their performance and reliability.

Obviously, the process of installing and activating any of the following plugins remains the same.

If you’re not sure about the process of installing a WordPress plugin, you can refer this beginner’s guide to learn different methods of installing a plugin in WordPress.

#1.1 Async JavaScript Plugin

If you want a standalone plugin to defer parsing of JavaScript, Async JavaScript should be your pick.

This tiny plugin offers all the necessary settings to tweak deferred loading of JS in WordPress.

How to Use Async JavaScript Plugin: Settings & Usage Guide

Steps to defer parsing of javascript in WordPress using a plugin:

  1. Navigate to WordPress Dashboard > Plugins > Add New.
  2. Search Async JavaScript Plugin in the plugin repository.
  3. Install and activate Async JavaScript Plugin.
  4. Head-over to WordPress Dashboard > Settings > Async JavaScript.
  5. Go to Settings tab of Async JavaScript Plugin.
  6. Check the box against ‘Enable Async JavaScript’ option and save changes to start deferring Javascript in WordPress.
  7. There are other options as mentioned below; You can tweak the relevant option as per your need.
  • enable asyns js for logged-in user
  • on cart/check out pages
  • quick settings
  • async javascript method
  • jQuery
  • scripts to Async
  • scripts to Defer
  • script Exclusion
  • plugin exclusions
  • theme exclusion
Async Javascript Plugin - Defer JS WordPress
Async Javascript Plugin – Defer JS WordPress

#1.2 Defer Parsing of JavaScript Setting in WP Rocket Plugin

WP Rocket is a power-pack of features when it comes to WordPress speed optimization.

You can easily defer loading of javascript using WP Rocket to speed up your site.

Steps involved to enable defer loading of JS using WP Rocket plugin:

  1. Install and active WP Rocket plugin.
  2. Go to WP Dashboard > Settings > WP Rocket.
  3. Under File Optimization enable Load JavaScript deferred option and save changes.
  4. Now test your site to check the results.
Load JavaScript deferred - WP Rocket
Load JavaScript deferred – WP Rocket

DO WE USE WP-ROCKET?

Hell, YES!

You can read, how we got load time under 1s using WP Rocket.

#1.3 Defer Parsing of JavaScript: W3 Total Cache

You can defer JavaScript loading in WordPress using W3 Total Cache plugin.

Steps to defer parsing of JavaScript using W3 Total Cache WordPress plugin:

  • Head-over to WordPress Dashboard > Plugins > Add New.
  • Search W3 Total Cache in the plugin repository.
  • Install and activate W3 Total Cache plugin.
  • Go over WP Dashboard > Performance (W3 Total Cache Settings) > Minify.
  • Scroll down to JS minify settings. You will see settings like shown in the image below.
  • Check/select options as shown in the image below. Click Save all settings and you are done.
  • Test your site using pagespeed test to see the results.
Defer JavaScript - W3 Total Cache
Defer JavaScript – W3 Total Cache

#1.4 Defer Loading of JavaScript in LiteSpeed Cache Plugin

LiteSpeed Cache is an amazing optimization plugin for LiteSpeed server hosting. But the general features of this plugin can be utilized on any server like LiteSpeed, Apache, NGINX, etc.

Steps to defer parsing of javascript in LiteSpeed Cache plugin:

  • Go to WP Dashboard > Plugins > Add New.
  • Search Litespeed Cache in the plugin repository.
  • Install and activate LiteSpeed Cache plugin.
  • Navigate to WP Dashboard > LiteSpeed Cache > Page Optimization > JS Settings.
  • Scroll down to Load JS Deferred And turn it ON and save changes.
  • Now test your website using pagespeed tool to check the result.
Load JS Deferred - LiteSpeed Cache Plugin
Load JS Deferred – LiteSpeed Cache Plugin

#1.5 Defer Parsing of JavaScript using Swift Performance Plugin

Swift Performance plugin has become a well-known name in the speed optimization category. Their free version is called ‘Swift Performance Lite’.

The process to delay loading of JS in WordPress using Swift Performance:

  • Head-over to WP Dashboard > Plugins > Add New.
  • Search Swift Performance Lite in the plugin repository.
  • Install and activate Swift Performance Lite
  • Navigate to WP Dashboard > Tools > Swift Performance > Settings > Optimization > Scripts.
  • Enable the option called Merge Scripts. Once you enable it, other related options will appear.
  • Now add the scripts to be deferred under the option called Deferred Scripts and Save changes.
  • Finally, test your website using speed test tool to see the result.
Deferred Scripts setting - Swift Performance Plugin
Deferred Scripts setting – Swift Performance Plugin

#1.6 Defer Parsing of JavaScript in WordPress using Speed Booster Pack

Speed Booster Pack also offers deferred loading of javascript out of the box. 

Step-by-step procedure to enable defer loading of js in Speed Booster Pack plugin:

  • Go to WordPress Dashboard > Plugins > Add New.
  • Search Speed Booster Pack in the plugin repository.
  • Install and activate Speed Booster Pack plugin.
  • Navigate to WP Dashboard > Speed Booster > Assets.
  • Scroll down to the option called Optimize JavaScript. Under this option choose Defer for deferred loading of JS.
  • Save changes and you’re done.
  • Now, test your site using pagespeed test tool to check the result.
Defer Javascript - Speed Booster Pack Plugin
Defer Javascript – Speed Booster Pack Plugin

#1.7 Defer Parsing of JavaScript: Autoptimize

Autoptimize another good plugin to optimize WordPress speed. This plugin also offers the option to defer load JS in WordPress.

Step-by-step process to defer parsing javascript using Autoptimize:

  • Navigate to WordPress Dashboard > Plugins > Add New.
  • Search Autoptimize in WordPress plugin repository.
  • Install and activate Autoptimize plugin.
  • Go to Dashboard > Settings > Autoptimize > JS, CSS & HTML.
  • Under JavaScript Options enable Optimize JavaScript Code and,
  • Then enable Do not aggregate but defer option and save changes.
  • Now Empty Cache and test your site using speed test tool to see the result.
Defer Javascript Loading - Autoptimize
Defer Javascript Loading – Autoptimize

#1.8 WP Fastest Cache to Defer Parsing of JavaScript

You can eliminate render-blocking JavaScript resources using WP Fastest Cache plugin. But this feature is available with the premium version only.

2. Defer JavaScript Parsing in WordPress via functions.php file

Yes, you can defer parsing of JavaScript in WordPress by adding a code snippet to function.php file.

This is one of the methods that you can use to Defer Parsing of JavaScript in WordPress without using a plugin.

As I have mentioned above this method is suitable for people who are comfortable with code editing in WordPress.

You might be thinking, but why?

First of all, functions.php is an important theme file. That means you might end up breaking your site easily if anything went wrong with the editing of functions.php file.

Also, there are different versions of the code snippet on the web to fix defer parsing of JavaScript in WordPress via functions file. Unfortunately, not all the code snippets work fine.

So you should be careful while using a code snippet to defer loading of JavaScript.

How to Edit functions.php File Safely

I always recommend using a child theme in WordPress in order to avoid code editing mess.

Because while editing the code, even if you miss a single comma (,) semicolon (;) or any other symbol/syntax, your website will break completely or partially. And you have to make extra efforts to recover the site.

If you’re not using a child theme, learn how to use a child theme in WordPress and its benefits.

For any reason, if you don’t want to implement a child theme now, you can use this plugin to add code to functions.php file of your theme without editing the original file.

Step-by-step process to Defer Parsing JavaScript in WordPress via functions.php

Take a complete backup before making any changes to the code.

I assume that you’re using a child theme. If you’re not, first create and activate a child theme to any trouble because of theme file editing.

  1. Go to your WordPress Dashboard > Appearance > Theme Editor
  2. Select/open functions.php file (of child theme) from theme files.
  3. Paste the code snippet given below at the end of functions.php file.
  4. You can specify JS files to exclude from defer in the array (‘jquery.js’).
  5. Finally, click Update File to save changes. That’s all.

The code snippet is to be pasted in functions.php file.

// Defer Parsing of JavaScript in WordPress via functions.php file
// Learn more at https://technumero.com/defer-parsing-of-javascript/ 

function defer_parsing_js($url) {
//Add the files to exclude from defer. Add jquery.js by default
    $exclude_files = array('jquery.js');
//Bypass JS defer for logged in users
    if (!is_user_logged_in()) {
        if (false === strpos($url, '.js')) {
            return $url;
        }

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

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

The above code snippet is using defer attribute to defer parsing of JavaScripts. You can replace the defer attribute with async attribute to parse JavaScript asynchronously. You can read more about async attribute and other methods to fix render-blocking JavaScript.

3. Defer Parsing of JavaScript without WordPress Plugin – Script Method

The script method explained above can be used in WordPress to defer loading of javascript. In WordPress, the above-mentioned code can be placed in HTML file just before the </body> tag using hook content option.

Most of the popular WordPress themes come with hook content provision. If you are not using the hook content option or it is not available in your theme. Then, either you can use a WordPress plugin to add the script to WordPress footer before </body> tag or you can place the script in the footer file just before the </body> tag manually.

Facing any difficulty adding the script to WordPress footer? Check out our detailed guide, to learn how to add code in WordPress header and footer easily.

Steps to defer load javascript in WordPress without using a plugin:

  1. Copy the code and paste that before the </body> tag (using a plugin or built-in theme hook) .
  2. Now replace script_to_be_deferred.js with the JavaScript to be deferred.
  3. Save changes and you’re done.
  4. Clear the cache, if there is any.
  5. Test your website again to see the result.

Test Results: After Defer Parsing of JavaScript

The following are the test results after defer loading of JavaScript.

PageSpeed Insights Result after fixing Defer Parsing of JavaScript
PageSpeed Insights Result after fixing Defer Parsing of JavaScript
GTmetrix result after implementing Defer Parsing of JavaScript
GTmetrix result after implementing Defer Parsing of JavaScript

Wrapping it up

Other than defer parsing of JavaScript, you can also use async attribute or inline JavaScript to remove render-blocking JavaScript. I have covered async attribute or inline JavaScript in another blog post, read that article here. In that article, I have also mentioned a few useful WordPress plugins to defer parsing JavaScript.

Although WordPress plugins are available to defer parsing of JavaScript. The above-explained script method is considered more appropriate by several experts and webmasters. But the people who use WordPress know that using a WordPress plugin is like bliss.

I hope this guide will help you to defer parsing of JavaScript. Let me know, which technique you use to defer parsing of JavaScript. If you are facing any problem implementing the above methods or have a question. Let me know via the comment section. I will be happy to answer.

Cheers!

Further readings:

General FAQ

What does defer mean in JavaScript?

Defer literally means ‘hold back’ or ‘delay’. If you use ‘defer’ attribute for parsing (loading) of JavaScript, JS will execute only after the HTML parsing has finished. This helps to improve pagespeed.

How do I remove render blocking JavaScript from my website?

To remove render blocking JavaScript, you can inline critical JS and defer all non-critical JS. Everything is explained step by step in this technumero’s tutorial.

How do I fix JavaScript defer parsing in WordPress?

You can do that with or without using a plugin. There are three methods to fix JavaScript defer parsing in WordPress properly: the script method, plugin method, and functions.php file method.

What’s the difference between async and defer JavaScript?

The ‘defer’ attribute delays JS execution until HTML parsing has been completed. However, with ‘async’ HTML parsing & script execution happens simultaneously and the script executes as soon as it’s ready. read more..

Photo of author
Shashank Singh
Shashank Singh is a web addict and amateur blogger. His current interests include blogging, SEO, and WordPress. See his social profiles to know him even better.
Disclaimer: Affiliate links of some product(s) are being used on this page, if you follow the link and make a purchase, we may receive compensation from respective companies. This compensation comes at no additional cost to you.

36 thoughts on “How to Defer Parsing of JavaScript Properly + WordPress Fix [Updated Guide]”

  1. Avatar of Dominic

    Awesome tutorial! Many people out there don’t know that plugins are not necessary if you want to defer JS in WordPress. We even had to publish a similar tutorial for our clients.

    Reply
    • Hey Dominic,
      Glad that you find it useful.
      Thanks for stopping by.

      Reply
  2. Avatar of Chukwuebuka Ogbuchi

    Please help, I am confused about this html and body tags, please tell me if the body tag the one in our template?

    Reply
    • Hey Chukwuebuka,
      If you are trying to implement in WordPress, you should look for hook content feature in your theme. Under hook content, there is closing tag in the footer. Hope it helps. Thanks for stopping by.

      Reply
  3. Avatar of Mithun

    I used this script and my website is blank i dont know what happened can you pls help me …

    Reply
    • Hey Mithun,

      To avoid such situations I always recommend to backup your files before making any changes in the code. In present situation you can access and edit the file (where you had pasted the script) via hosting cPanel > File Manager. Or using FTP client.
      Hope it helps.

      Reply
  4. Avatar of charan

    This is what am looking, my blog loading slow because of blocking css & js scripts. I will implement the code, hope this code will fix my blog problem. Thanks, Shashank! for sharing and expecting more posts like this. Will visit again.

    Reply
    • Hey Charan,
      Thanks for stopping by.
      Looking forward to listen more from you.

      Reply
  5. Avatar of Vishal

    Hi Shashank,

    Thanks for your tutorial. My theme don’t have hook option so i tried to put the code in footer before /body but it is not working, what to do.

    Do you have any code to be put in function.php with hook command for WordPress site.

    Reply
  6. Avatar of Henry Okonkwo

    Hi, thanks for the article. It worked well on my blog.

    Reply
    • Hey Henry,
      Glad that I could help.
      Thanks for dropping by.

      Reply
    • Hey Bernadette,
      I understand your concern. Setup of all the plugins with screen captures is in the mentioned article. Check out the lower-half of the article. Hope it helps. Thanks for stopping by!

      Reply
  7. Avatar of Fırat

    Helllo,

    Thanks for the great tutorial, but it did not help me. Do we need to delete those js lines after including them in your code?

    Thanks!

    Reply
    • Hey Fırat,

      No, you need not delete JS. All you need is, to place JS path in the code and paste the code to HTML file just before the tag. You may also check this article to learn how to Add Code to WordPress Header and Footer easily.
      Hope it helps. Thanks for stopping by!

      Reply
  8. Avatar of Sumit Kumar Gupta

    Hello sir,
    I am using Autoptimize, W3 Total Cache and WP Optimize plugin together.

    So please tell me should we use all plugin together or not?
    Sir, I have changed our theme and after changing our theme defer javascript problem enables, so how could I fixe this?

    And last question is how to tick the follow button below comment box automatic Please tell me.

    Reply
    • Hey Sumit,
      Autoptimize and W3 Total Cache is used for similar purpose. You can choose one of them for your requirements because there is no point of using two different plugins for similar purpose. WP-Optimize is for WP database optimization.
      As long you are NOT facing any specific issue using these plugin together, you may use them.
      This article How to Add Subscribe to Comments in WordPress covers your last question.

      Reply
  9. Avatar of Asdeideas

    Hi!
    First thing I’ve tried to defer parsing of JavaScript was to activate the option in the cache plugin I use (Litespeed Cache), but I had some visualization problems about Rev Slider and translation plugin also(Transposh), so I excluded the corresponding JS of deferring, but not fixing the error… After that, did the same but using Fast Velocity Minify plugin instead, same results. Maybe adding the code to functions.php skipping these problematic JS could be the solution but, how can I exclude it by code?

    Many thanks for the help!

    Reply
    • Hey,

      You can follow the link and instructions to setup recommended WordPress plugins to resolve your issue.
      Hope that helps. Thanks for stopping by!

      Reply
  10. Avatar of Ben

    I just used the “Code to Defer Multiple JavaScripts in One-go” in my footer.php file and now I have a 100% score for deferring JS parsing in GTMetrix! Thanks a ton!

    Reply
  11. Avatar of Faby

    Hi and thanks for this article. I’ve tried to insert the code but GTmetrix continues warning me about the problem. I’ve placed it into the footer.php file of my WordPress site just before the tag, pasting the two scripts reported by the site, so I think it’s ok. Maybe I need to clear my site cache? But even if that was the case, I don’t know how to do it considering that I don’t have cache plugins.

    Reply
  12. Avatar of Shashank Singh

    Hey Faby,

    That’s strange. The script worked fine for many WP users. If it’s not working for you for some reason, you can try one of the WordPress plugins mentioned.
    Thanks for stopping by!

    Reply
  13. Avatar of Sathik

    I just implement the code on my website (html) but it doesn’t work. And I don’t see any improvement in my speed optimization, kindly suggest me that some other code if you have.

    Reply
    • Avatar of Shashank Singh

      Hey Sathik,

      The same worked for many readers. I’m surprised that it’s not working in your case.
      Maybe take help of someone (local) with better coding skills to implement the code.
      Thanks for dropping by!

      Reply
  14. Avatar of James Johnson

    I’ve used the funtions.php method for my WordPress site. It does what its meant to but changes the font of my website. Does anyone know a go-around or fix for this?
    Thanks

    Reply
    • Avatar of Shashank Singh

      Hi James,

      You can exclude the conflicting file by adding that to the array $exclude_files = array('jquery.js, your_file_name.js');
      First, you have to figure out which JS file is causing the issue. Once you identified the file, you can add that in place of your_file_name.js to exclude that from defer.
      All the best!
      Thanks for stopping by!

      Reply
  15. Avatar of Mat

    Hi,
    I really like the way you explain everything. I’m about to implement the code you’re suggesting to defer multiple JS in one go and have a question for you. When you replace the link in element.src = “script_to_be_deferred.js”; with the actual one, do you still need to keep the original JS in the html code?

    Thanks

    Reply
    • Avatar of Shashank Singh

      Hey Mat,

      Yes, the original JS file will remain in the HTML code of the website.

      I hope that helps! Thanks for stopping by!

      Reply
  16. Avatar of Anurag tripathi

    I have created a website in CodeIgniter but “Defer parsing of JavaScript” is very low for page speed test. Please consider my suggestion thanks

    Reply
  17. Avatar of Tomas

    Hi,
    I just implement the code on my website but it doesn’t work – no change in GTmetrix result. I did exactly what you suggest:

    Insert this code in the HTML file just before the tag.

    But no change. Do I need to do something else? I did it for youtube script, you can see it here:
    (site URL removed)
    Thanks a lot,
    Tomas

    Reply
    • Avatar of Shashank Singh

      Hey Thomas,

      The code should work as it worked for many of us. I noticed that your site is a non-WordPress one. So you can try using ‘defer’ or ‘async’ attribute in the specific JS. Here is a guide explaining how to use ‘defer’ or ‘async’ attribute to defer JS parsing: Remove render-blocking JavaScript.
      Good luck.
      Thanks for stopping by!

      Reply
  18. Avatar of Daniz Arkan

    Great, by the way, how to use defer parsing javascript in laravel?

    Reply
  19. Avatar of Ken Albert

    Hi,

    function defer_parsing_js($url) {
    //Add the files to exclude from defer. Add jquery.js by default
    $exclude_files = array(‘jquery.js’);
    //Bypass JS defer for logged in users
    if (!is_user_logged_in()) {
    if (false === strpos($url, ‘.js’)) {
    return $url;
    }

    foreach ($exclude_files as $file) {
    if (strpos($url, $file)) {
    return $url;
    }
    }
    } else {
    return $url;
    }
    return “$url’ defer=’defer”;

    }
    add_filter(‘clean_url’, ‘defer_parsing_js’, 11, 1);

    How to use this when I want to used it on multiple js file?

    Reply
    • Avatar of Shashank Singh

      Hey Ken,

      if your site is on WordPress, this script works for all the JS files (except those are excluded under this array $exclude_files = array(‘jquery.js’);. For example, you don’t want to defer a js file named (xyz.js) then you’ll write array as $exclude_files = array(‘jquery.js’, ‘xyz.js’);. In this case, all JS files ‘ll be deferred except these two: jquery.js’, ‘xyz.js’.
      I hope that helps.
      Thanks for stopping by!

      Reply

Leave a Comment

Your email address and website details will not be published. Required fields are marked with *.