fbpx
Blog

How to Defer Parsing of JavaScript in WordPress

How to Defer Parsing of JavaScript in WordPress, featured image

A critical measure of your website performance is page speed. Page speed is the time that a browser takes for rendering a website. Faster load times ensure that a larger proportion of your visitors stay on your website as it loads up. Page speed also partially determines the rank of your website in search engine results. Therefore, speeding up a WordPress website is often at the top of a site owner’s wish list.

In this tutorial, we’ll discuss deferring parsing of JavaScript during web page load — a key technique to remove dead weight from your website.

Page speed is an important part of the user experience that depends on many things. This article presumes that you have checked an underlying factor — running your website on a sufficiently fast WordPress host.

Why Defer Parsing of JavaScript?

To understand the technique of deferring parsing of JavaScript, let’s take a step back and analyze how a web browser renders a page. When your browser sends a request to your web server, the page sent back by the server is downloaded in the form of an HTML document. This HTML document contains text, code that renders various DOM elements, and resources such as images, stylesheets, and scripts.

The browser reads this HTML markup line by line. Additionally, the resources present on the page need to be downloaded. By default, the browser sequentially downloads these resources as it finds them in the document. The rendering of the web page only resumes once a resource has been downloaded.

Large resources adversely affect page load time. As images form a significant portion of the page size, it’s recommended to optimize images for your WordPress site. For JavaScript files, you need to identify which scripts are necessary to render your page correctly. You can defer the download of non-essential scripts to speed up your webpage.

In the next section, we’ll look at ways to identify which scripts are necessary for rendering your page.

Which Scripts to Defer?

For a relatively small website that uses minimal JavaScript, no scripts may be essential for loading the page. However, if you manage a more complex website, a careful analysis of all scripts on your website can reveal which scripts are essential for page loads.

One way of performing this analysis is removing scripts one by one and checking if there are any errors in the JavaScript console during page load. However, this process requires considerable knowledge of JavaScript and web technologies.

An easier method to assess which scripts are critical to your page load is to use a speed test tool such as GTmetrix. Enter the URL of your website and wait for the tool to assess it. In the results page, head over to the PageSpeed tab and expand the “Defer parsing of JavaScript” section. This section shows you a list of non-essential scripts that are loaded during the rendering process.

Defer Parsing of JavaScript in GTMetrix

Async vs. Defer Attributes

There are two ways to ensure that downloading a script doesn’t interfere with the rendering of a web page.

First, you can add an async attribute to the script tag. This tells the browser to asynchronously load the script. In other words, the browser starts downloading the resource as soon as it encounters it in the code but continues parsing the HTML while the resource is still being downloaded. The sample script tag below shows how to add the async attribute:

<script src="path/to/script" async></script>

Second, you can add a defer attribute to the script tag. This tells the browser not to download the resource until the parsing of the page is complete. Once the parsing and rendering are done, the browser downloads the list of deferred scripts that it has encountered earlier. The sample script tag below shows how to add the defer attribute to an HTML page:

<script src="path/to/script" defer></script>

The primary difference between the defer and async attributes is when the resource will be downloaded.

Say you have two scripts: A and B. B appears in the code after A, B has a dependency on A, but A is significantly larger than B.

If you use async, it may be possible for B to finish downloading before A has been completely downloaded. This will lead to an error, as B will be executed in the absence of A.

However, if you use defer, A and B will be sequentially downloaded at the end, which won’t lead to an error.

If you have only a few scripts in the rendering path, you wouldn’t find any difference between the use of async and defer. However, if you have a complex web application, it may be a good idea to use defer to ensure inter-dependencies are satisfied.

Let’s now discuss the ways to defer the download of scripts in WordPress.

Defer Parsing of JavaScript in WordPress

1. Edit the functions.php File

If you have worked in WordPress development, you know that it’s not recommended to add scripts directly through the HTML markup. Instead, you should use built-in WordPress functions to request for resources.

So if you would like to add an async or defer attribute to any of your scripts, you should add the following function to your theme’s functions.php file:

add_filter('script_loader_tag', 'add_defer_tags_to_scripts');
function add_defer_tags_to_scripts($tag){
    # List scripts to add attributes to
    $scripts_to_defer = array('script_a', 'script_b');
    $scripts_to_async = array('script_c', 'script_d');
 
    # add the defer tags to scripts_to_defer array
    foreach($scripts_to_defer as $current_script){
        if(true == strpos($tag, $current_script))
             return str_replace(' src', ' defer="defer" src', $tag);
    }
 
    # add the async tags to scripts_to_async array
    foreach($scripts_to_async as $current_script){
        if(true == strpos($tag, $current_script))
             return str_replace(' src', ' async="async" src', $tag);
    }
     
    return $tag;
 }

Don’t forget that before you add the defer and async attributes to the script tags, you also need to enqueue each script so that WordPress can access it:

add_action('wp_enqueue_scripts', 'enqueue_custom_js');
function enqueue_custom_js() {
    wp_enqueue_script('script_a', get_stylesheet_directory_uri().'/script_a.js');
    wp_enqueue_script('script_b', get_stylesheet_directory_uri().'/script_b.js');
    wp_enqueue_script('script_c', get_stylesheet_directory_uri().'/script_c.js');
    wp_enqueue_script('script_d', get_stylesheet_directory_uri().'/script_d.js');
}

2. Use a Plugin

Editing the source code through the functions.php file may not be ideal for all. If you are not tech-savvy, you can simply use a plugin to defer parsing of JavaScript in your WordPress site.

Async JavaScript

Async JavaScript is a free plugin that you can download and install on your WordPress site to perform this task.

To enable the feature, check the Enable Async JavaScript option in the settings area of the plugin. Then, scroll down to the Async JavaScript Method section and select if you would like to use the async or defer method.

Async JavaScript Plugin UI

For more advanced options, scroll down the page. Here, you can list the scripts you want to apply the async and defer tags to. Next, you can add a list of scripts to exclude too. You can also list the plugins and themes to be excluded from any changes that this plugin makes.

Async JavaScript Insert Scripts

Autoptimize

The option to defer parsing your scripts is also available as part of the Autoptimize plugin created by the same author as Async JavaScript.

In the plugin’s settings page, check the Optimize JavaScript Code option and your non-essential scripts will be deferred and moved to the footer. In the Extra tab, you can also list the scripts you want to add the async attribute to.

Autoptimize Plugin Settings

Wrapping Up

In this tutorial, we first discussed the importance of page speed and how the rendering of JavaScript works. Then, we explored the reasons why you should defer the parsing of JavaScript.

Finally, we looked at two options through which you can achieve it in WordPress. You can either edit the functions.php file to add the async or defer attributes to your script tags or use a plugin such as Async JavaScript or Autoptimize to optimize your scripts.

Any questions on how to defer parsing of JavaSript in WordPress? If so, please feel free to ask away in the comments below.

Share This Article:
Facebook Twitter

Related Posts

Leave a Reply

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