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

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 deferred loading of JavaScript help to speed up your website?

Get WP Rocket WordPress Cache Plugin.
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.

Table of Contents [hide]

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.

A2 Hosting - 72% OFF on Turbo (Up To 20X Faster) Hosting

The browser renders the components serially from the top towards 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 stop 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 or async

Now you know that there are two attributes – defer or 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 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 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 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 the 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, effect, or 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.

And by making your site load faster, you also improve your search ranking on desktop as well as mobile.

Do you know, good web hosting is a must for better pagespeed?
If you are already using good web hosting?
Awesome, let’s skip to defer parsing of JavaScript.
Not sure? whether your hosting is as good as your website deserves, don’t worry. We recommend Cloudways and Kinsta Hosting for better sitespeed.
Read our Kinsta Review.

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 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 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

#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 in 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!

Source :
https://technumero.com/defer-parsing-of-javascript/

Exit mobile version