How to Defer Parsing of JavaScript in WordPress? Print

  • 0

If you have tested your WordPress website speed in a website speed testing tool like GTMetrix, you may have come to know it with Defer Parsing JavaScript.

GTMetrix

When any website visitors open your website on their browser, it will open the HTML content of your website. Then, it will load your website from top to bottom, and if there is any JavaScript, it will stop rendering the page until it completely fetches or parses the JavaScript. It may take some time for your browser to download or parse the JavaScript, and this wait time may be annoying to your website visitors before they can see the core content of your website. 

To prevent your website from slowing down, you can defer certain JavaScript loading before your core content which can be helpful for your website. 

Below we have explained two methods using which you can defer the parsing of JavaScript.

  • Async
  • Defer

In Async, you need to add an async attribute in the script tag, and it will ask the browser to load the script asynchronously. The browser will start downloading the resources once it encounters them in the code; however, it will continue to parse the HTML between the other resources that are still being downloaded. 

Here is the sample script tag to add the async attribute to the HTML page –

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

You need to add a defer attribute in the script tag in Defer. It will ask the browser not to download the resource until the page parsing is completed. Once it is done with parsing and rendering, the browser will download all the deferred scripts encountered. 

Here is the sample script tag to add the defer attribute on the HTML page

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

Parse JavaScript in WordPress

1. Defer JavaScript via functions.php File

You can add the defer attribute inside your JavaScript files if you don't want to use any plugins. Add the below code to your functions.php file:

function defer_parsing_of_js( $url ) {
    if ( is_user_logged_in() ) return $url; //don't break WP Admin
    if ( FALSE === strpos( $url, '.js' ) ) return $url;
    if ( strpos( $url, 'jquery.js' ) ) return $url;
    return str_replace( ' src', ' defer src', $url );
}
add_filter( 'script_loader_tag', 'defer_parsing_of_js', 10 );

This will ask WordPress to add the defer attribute to all your JavaScript files except jQuery.

2. Defer JavaScript using the WordPress plugin

Async JavaScript

It is a free WordPress plugin you can easily enable, as shown in the image below, or choose the async or defer method per your requirement. 

Async JavaScript

You can enter or exclude the script you want to parse using the async or defer method as an advanced option.

 

Was this answer helpful?

« Back

chat