Defer Parsing of JavaScript

Table Of Contents hide
20 min read

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

Learn how to improve your page speed score by deferring the parsing of JavaScript and addressing the ‘Eliminate render-blocking of JavaScript’ warning in Google PageSpeed Insights. The latest version of Google PageSpeed Insight now refers to this issue as ‘Eliminate render-blocking resources,’ encompassing JavaScripts and CSS. In this article, we’ll delve into what defer parsing of JavaScript entails, how to properly implement it, the reasons behind deferring parsing of JavaScript, methods for identifying render-blocking JavaScripts that need deferring, and how to defer multiple JavaScripts simultaneously. We’ll also explore how to defer parsing of JavaScript in WordPress, both with and without plugins, and elucidate how defer loading of JavaScript contributes to accelerating your website’s performance.

 

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

How to Defer Parsing of JavaScript

In simple terms, we aim to address the issue of render-blocking JavaScripts not by outright removing them from the website code (deleting), but by deferring their loading. This approach ensures that these JavaScripts no longer impede the loading (rendering) of meaningful content, allowing the website’s essential elements to display promptly. If the technical terminology initially seems overwhelming, there’s no need to worry! I’ll guide you through each step in straightforward language, enabling you to follow along at your own pace and implement the methods to resolve the ‘Eliminate render-blocking resources’ issue on your website or blog.

What is Defer Parsing JavaScript

A web page comprises various components such as HTML, CSS/Stylesheets, JavaScript, and graphical elements like images and icons. These components are structured in the code of the web page, stacked one over another. When a user enters your website’s URL in the browser’s address bar and hits enter, the browser establishes a connection with the server hosting your website. After the connection is established, the browser begins rendering the components of the webpage to display it. The rendering occurs serially, from the top to the bottom of the webpage. Each component is rendered in order, with the browser stopping rendering when it encounters JavaScript on the page. It downloads and executes the JavaScript before continuing to render the next component. This pause in rendering occurs each time the browser encounters JavaScript, blocking the critical rendering path.

To address this issue, Google Engineers recommend deferring non-critical JavaScript.

Now, the question remains, what is Defer Parsing of JavaScript? Defer Parsing of JavaScript is the process of using the defer or async attribute with JavaScript to avoid blocking the initial rendering of a web page. These attributes instruct the web browser to parse and execute the JavaScript either in parallel (asynchronously) or after (defer) the parsing of the HTML of a web page. This way, visitors don’t have to wait as long to see the meaningful content of the web page.

Difference Between Defer and Async

Now that you are aware of two attributes, defer and async, which can be employed to defer JavaScript loading, let’s delve into how the <script> tag operates.

Legend Defer Parsing of JavaScript - async vs defer attribute legend async vs defer attribute <script>

script tag script tag

When we utilize the <script> tag to incorporate a script in our code, HTML parsing continues until the script file is encountered. At that point, parsing is halted until the script file is downloaded and executed. Suitability: Not recommended in most cases. <script defer>

script defer attribute script defer attribute

When the defer attribute is added to a script tag, the script file is downloaded concurrently with HTML parsing, but the downloaded script executes only after the HTML parsing is complete. Suitability: For non-critical script files. <script async>

Defer Parsing of JavaScript - script async attribute script async attribute

When the “async” attribute is used with the script tag, the script file downloads during HTML parsing. However, HTML parsing pauses briefly just to execute the downloaded script file. This is suitable for critical script files that cannot be inline. <script async>

Defer loading of JS & PageSpeed Insights recommendation

When you test a website using the Google PageSpeed Insights Tool, you receive warnings and recommendations to address any issues or errors detected on the site.

Defer Parsing of JavaScript - Google PSI - Render blocking resources - JavaScripts to be deferred Google PSI – Render blocking resources – JavaScripts to be deferred

The warning in PageSpeed Insights (PSI) regarding “render-blocking resources” indicates that certain resources, specifically JavaScript (JS) and CSS, are impeding the initial display of your page. The recommendation is to address this issue by delivering critical JS and CSS inline, and deferring the loading of non-critical JS and styles. This warning arises when the loading of certain JavaScript elements on your website hinders the rendering of essential content, causing visitors to wait longer to view meaningful content. In essence, site speed testing tools like PageSpeed Insights highlight this warning if your site includes JavaScript elements that obstruct the timely loading of crucial content, and it requires corrective action.

Critical vs Non-critical JavaScript: Explained

According to the recommendation from Google PageSpeed Insights (PSI), the suggestion is to incorporate “critical JS” directly within the HTML code (inline) and delay the loading of “non-critical JS” until after the initial meaningful content of the webpage has loaded. Let’s clarify the terminology:

  • Critical JavaScripts: These are essential scripts required for optimized critical rendering.
  • Non-critical JavaScripts: These scripts can be deferred until after the first meaningful content (the first paint) of the webpage has loaded.

Inline Delivery involves loading a resource, in this case, JavaScript, directly within the HTML code rather than calling or importing it separately.

As for why JavaScript blocks the critical rendering path in the first place, we’ll delve into that in the next section along with other reasons explaining why deferring JavaScript parsing is beneficial.

 

Why You Should Defer Parsing of JavaScript

JavaScript Execution: is a Heavier Task

JavaScript significantly impacts the speed of your website. When a web browser encounters a JavaScript script, it prioritizes executing the script before continuing to load the HTML containing the content users want to see. Executing JavaScript is a resource-intensive task for a browser, especially for larger scripts, and it takes more time compared to rendering the meaningful content (the first paint) of the webpage. As a result, JavaScript affects the critical rendering path, slowing down the overall page speed of your website. The solution is to defer the execution of this resource-intensive JavaScript task, allowing the critical rendering path to proceed smoothly.

Pagespeed: is now a Ranking Factor

The speed of a website has been a ranking signal for about a decade now. Google officially announced in a blog post on Google Webmaster Central Blog that site speed had become a ranking signal. In a subsequent blog post in 2018, Google revealed that they had started using page speed as a ranking factor in mobile search rankings. Given Google’s declaration that page speed impacts both desktop and mobile search rankings, optimizing site speed has become a crucial element of technical SEO. Consequently, Google PageSpeed Insights Tool recommends deferred parsing of JavaScript as one of the solutions to eliminate render-blocking JavaScript in above-the-fold content.

Related Post  Online Business Startup Checklist During COVID-19

User Experience: decides Your Site’s Success

JavaScript significantly impacts user experience (UX) by slowing down pagespeed and blocking the rendering of the first paint, which is the meaningful content of a webpage. This delay results in a longer loading time and a frustrating wait for users to access the content, leading to a poor user experience. Since users generally dislike slow-loading websites, studies indicate that they tend to leave such sites early and seek alternatives. To enhance user engagement and conversion rates, it’s crucial to prioritize pagespeed improvement by deferring non-critical JavaScript(s).

Reasons to Defer Loading of JavaScript: Summing it up

As mentioned earlier, the browser starts downloading and executing scripts as soon as it encounters them in the HTML, even though most JavaScripts are only utilized once the entire webpage is loaded, such as for animations, effects, and functionalities. Therefore, deferring the loading of JavaScript until after the content has loaded is a sensible approach. This ensures that deferred loading of JavaScript does not impact the critical render path, leading to an accelerated website speed and an improved user experience for readers. Statistics indicate that speeding up your site’s loading time can enhance search rankings on both desktop and mobile platforms.

Now that you understand what defer parsing of JavaScript is and why it’s beneficial, it’s time to identify which JavaScripts on your website are causing issues and need to be deferred. If you already know which JavaScripts are blocking the critical rendering path on your website, you can skip the following section and proceed to the implementation part. Otherwise, continue reading.

How to Find Render-blocking JavaScript(s)

JavaScripts that hinder the rendering of meaningful content are labeled as ‘Render Blocking JavaScripts’ and should be deferred. To identify these render-blocking JavaScripts, you can utilize site speed testing tools. There are several reliable and trusted tools available for analyzing a website’s site speed and loading time. I’m sharing with you the most dependable tools for pagespeed testing. Test your site using these tools and make a note of the results so that you can compare them before and after implementing defer parsing of JavaScripts.

1. PageSpeed Insights by Google

PageSpeed Insights by Google PageSpeed Insights by Google

Google PageSpeed Insights (PSI) is a specialized pagespeed testing tool developed by Google. Assess your website’s performance using the Google PSI Tool to identify render-blocking JavaScript(s). The results from the PageSpeed Insights Tool provide details about warnings along with recommended solutions and fixes.

2. GTmetrix

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

GTmetrix is another valuable free tool for evaluating site speed. Utilize GTmetrix to examine your site and identify which JavaScripts require deferring.

3. Pingdom Tools

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

SolarWinds Pingdom Tools are widely used for site speed testing. You can assess your site with Pingdom Tools to determine the number of JS requests and their impact on the overall number of requests. Now that you’ve identified the JavaScript(s) causing slowdowns on your site, let’s explore how to address this issue by deferring non-critical JavaScript(JS).

Test Results: Before Defer Parsing of JavaScript

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

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

Defer Parsing of JavaScript - GTmetrix Result before Defer Parsing of JS GTmetrix Result before Defer Parsing of JS

How to Defer Parsing of JavaScript [Step by step]

You should use the following code to defer parsing JavaScript. Insert this code in the 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 Deferring Parsing JavaScript using the script:

Backup: Don’t forget to take a complete backup before making any changes in the code. If something goes wrong, you can use that backup to revert.

Copy and Paste: Copy the code and paste it in the HTML file just before the </body> tag (near the bottom of the HTML file).

Replace Link: Replace script_to_be_deferred.js with the link of the JavaScript that is to be deferred. You can copy the link of JavaScript(s) (which Google PageSpeed tool suggests deferring) from Google PageSpeed Insights tool results for your website.

Save Changes: Save changes. And you are done.

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 a little modification. In the following code, replace defer1.js, defer2.js, and defer3.js, etc. with the links of the 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>

Replace the values in the links array with the actual links of the scripts you want to defer. This modification will defer the specified scripts in one go.

How to Defer Parsing of JavaScript in WordPress

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 to this beginner’s guide to learn different methods of installing a plugin in WordPress.

Here are some recommended plugins:

Async JavaScript:

Link: Async JavaScript

Description: Async JavaScript allows you to defer parsing of JavaScript files, either by excluding them from the deferral process or by adding an “async” or “defer” attribute.

Flying Scripts:

Link: Flying Scripts

Description: Flying Scripts allows you to defer the loading of JavaScript files, improving page loading times. It also provides options to exclude specific scripts from deferral.

WP Rocket:

Link: WP Rocket

Description: WP Rocket is a premium caching plugin that includes an option to defer the loading of JavaScript files. It is a comprehensive performance optimization plugin.

Perfmatters:

Link: Perfmatters

Description: Perfmatters is a lightweight performance plugin that includes an option to defer JavaScript loading. It provides various performance optimization features.

Remember to carefully configure these plugins according to your site’s requirements and test the performance after implementation.

#1.1 Async JavaScript Plugin

If you prefer a standalone plugin for deferring parsing of JavaScript in WordPress, Async JavaScript is a suitable choice. This compact plugin provides all the necessary settings to customize the deferred loading of JavaScript on your WordPress site.

How to Use Async JavaScript Plugin: Settings & Usage Guide

Follow these steps to defer parsing of JavaScript in WordPress using the Async JavaScript plugin:

  • Navigate to your WordPress Dashboard > Plugins > Add New.
  • Search for “Async JavaScript Plugin” in the plugin repository.
  • Install and activate the Async JavaScript Plugin.
  • Go to WordPress Dashboard > Settings > Async JavaScript.
  • In the Settings tab of the Async JavaScript Plugin:
  • Check the box next to the ‘Enable Async JavaScript’ option.
  • Save changes to initiate the deferred JavaScript loading in WordPress.

Additional options include:

  • Enable Async JavaScript for logged-in users.
  • Apply settings on cart/check-out pages.
  • Quick settings for easy configuration.
  • Choose the async JavaScript method.
  • Manage jQuery settings.
  • Specify scripts to be async.
  • Specify scripts to be deferred.
  • Exclude specific scripts.
  • Exclude plugins and themes.

 

Async Javascript Plugin - Defer JS WordPress

#1.2 Defer Parsing of JavaScript Setting in WP Rocket Plugin

If you’re using the WP Rocket plugin for WordPress speed optimization, you can take advantage of its features to defer loading of JavaScript and enhance your site’s speed. Follow these steps to enable deferred loading of JS using the WP Rocket plugin:

  • Install and activate the WP Rocket plugin.
  • Go to your WordPress Dashboard > Settings > WP Rocket.
  • Under File Optimization, enable the Load JavaScript deferred option.
  • Save the changes.

After completing these steps, test your site to assess the improvements in speed.

Load JavaScript deferred - WP Rocket

Read the Review for WP-ROCKET.

#1.3 Defer Parsing of JavaScript: W3 Total Cache

To defer the parsing of JavaScript in WordPress using the W3 Total Cache plugin, follow these steps:

  • Go to your WordPress Dashboard > Plugins > Add New.
  • Search for “W3 Total Cache” in the plugin repository.
  • Install and activate the W3 Total Cache plugin.
  • Navigate to WP Dashboard > Performance (W3 Total Cache Settings) > Minify.
  • Scroll down to the JS minify settings section.
  • Adjust the settings as shown in the provided image.
  • Check/select the options according to the image and click “Save all settings.”
Related Post  BCG Matrix Guide

After completing these steps, test your site using a pagespeed test to observe the results.

Defer JavaScript - W3 Total Cache

#1.4 Defer Loading of JavaScript in LiteSpeed Cache Plugin

To defer parsing of JavaScript using the LiteSpeed Cache plugin, follow these steps:

  • Go to your WordPress Dashboard > Plugins > Add New.
  • Search for “LiteSpeed Cache” in the plugin repository.
  • Install and activate the LiteSpeed Cache plugin.
  • Navigate to WP Dashboard > LiteSpeed Cache > Page Optimization > JS Settings.
  • Scroll down to Load JS Deferred and turn it ON, then save changes.

After completing these steps, test your website using a pagespeed tool to check the results.

Load JS Deferred - LiteSpeed Cache Plugin

#1.5 Defer Parsing of JavaScript using Swift Performance Plugin

To delay the loading of JavaScript in WordPress using the Swift Performance Lite plugin, follow these steps:

  • Go to your WordPress Dashboard > Plugins > Add New.
  • Search for “Swift Performance Lite” in the plugin repository.
  • Install and activate the Swift Performance Lite plugin.
  • Navigate to WP Dashboard > Tools > Swift Performance > Settings > Optimization > Scripts.
  • Enable the option called “Merge Scripts.” Once enabled, other related options will appear.
  • Add the scripts to be deferred under the option called “Deferred Scripts” and save changes.

After completing these steps, test your website using a speed test tool to see the results.

Deferred Scripts setting - Swift Performance Plugin

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

To enable deferred loading of JavaScript in WordPress using the Speed Booster Pack plugin, follow these steps:

  • Go to your WordPress Dashboard > Plugins > Add New.
  • Search for “Speed Booster Pack” in the plugin repository.
  • Install and activate the 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.

After completing these steps, test your site using a pagespeed test tool to check the result.

Defer Javascript - Speed Booster Pack Plugin

#1.7 Defer Parsing of JavaScript: Autoptimize

To defer parsing of JavaScript in WordPress using the Autoptimize plugin, follow these steps:

  • Go to your WordPress Dashboard > Plugins > Add New.
  • Search for “Autoptimize” in the WordPress plugin repository.
  • Install and activate the Autoptimize plugin.
  • Navigate to Dashboard > Settings > Autoptimize > JS, CSS & HTML.
  • Under JavaScript Options, enable “Optimize JavaScript Code” and,
  • Enable the “Do not aggregate but defer” option, and save changes.
  • Empty the cache, and test your site using a speed test tool to see the result.

By completing these steps, you’ll defer parsing of JavaScript using the Autoptimize plugin in WordPress.

Defer Javascript Loading - Autoptimize

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

Certainly, you can defer parsing of JavaScript in WordPress by adding a code snippet to the functions.php file. However, it’s important to exercise caution while editing this file, as any mistakes can potentially break your site.

Here are the general steps to defer parsing of JavaScript in WordPress through the functions.php file:

Safely Edit functions.php File:

  • Consider using a child theme to avoid issues with code editing. This is recommended because any mistakes in the code can break your site.
  • If you’re not using a child theme, you can use a plugin to add code to the functions.php file without directly editing it.

Use a Child Theme:

  • If you’re not using a child theme, it’s advisable to learn how to set up and use one to ensure the safety of your site during code modifications.

Code Snippet:

  • Add the following code snippet to your theme’s functions.php file. Make sure to replace "your_script.js" with the actual URL of the JavaScript file you want to defer.

function defer_parsing_of_js($url) {
if (is_user_logged_in()) return $url; // don’t defer if logged in

if (false === strpos($url, ‘.js’)) return $url;
if (strpos($url, ‘jquery.js’)) return $url;

return “$url’ defer “;
}
add_filter(‘clean_url’, ‘defer_parsing_of_js’, 11, 1);

This code snippet checks if the user is logged in, skips jQuery, and defers the loading of other JavaScript files.

Save Changes:

  • After adding the code snippet, save the changes to the functions.php file.

Test Your Site:

  • Test your site to ensure that the JavaScript deferment is working as expected.

Remember to be cautious while making changes to the functions.php file, and always have a backup of your site before making significant modifications. If you’re uncomfortable with code editing, consider using a reliable plugin for deferring JavaScript in WordPress.

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

Before making any changes to the code, it’s crucial to take a complete backup of your WordPress site. Assuming you’re using a child theme, follow these steps:

Access Theme Editor:

  • Go to your WordPress Dashboard.
  • Navigate to Appearance > Theme Editor.

Select functions.php File:

In the Theme Editor, select or open the functions.php file of your child theme from the list of theme files.

Paste Code Snippet:

  • Paste the provided code snippet at the end of the functions.php file. This code snippet includes a function for deferring the parsing of JavaScript.
  • You can specify JavaScript files to exclude from defer in the array ('jquery.js' is excluded by default).
  • Update File:

After pasting the code, click on the “Update File” button to save the changes.

Here’s the code snippet for deferring parsing of JavaScript in WordPress via the functions.php file:

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:

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

// 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);

This code snippet uses the defer attribute to defer parsing of JavaScript. If you prefer parsing JavaScript asynchronously, you can replace the defer attribute with the async attribute in the code.

Test Results: After Defer Parsing of JavaScript

Here are the test results after implementing the 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

Apart from deferring parsing of JavaScript, you also have the options of using the async attribute or inline JavaScript to address render-blocking issues. I’ve discussed the async attribute and inline JavaScript in another blog post, where I’ve also highlighted some useful WordPress plugins for deferring parsing of JavaScript. While WordPress plugins offer convenience, the script method explained above is often considered more suitable by experts and webmasters.

For those familiar with WordPress, using a plugin is like bliss. I hope this guide proves helpful for deferring parsing of JavaScript. Feel free to share which technique you prefer for deferring parsing of JavaScript. If you encounter any issues implementing the methods mentioned above or have any questions, let me know in the comments, and I’ll be happy to assist.

10 Comments

  1. This is one of the best posts I’ve read on this forum. The information in the article helped me understand more about a new topic that I had never known.

  2. I was just on your website and found a lot of useful information, especially on this blog page. A lot of people have said things about your articles

Leave a Reply

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

CommentLuv badge