Table of Contents

Do you think dealing with JavaScript is challenging? You’re not alone. JavaScript is difficult to learn because it is powerful: it adds dynamic and interactive elements to the web page to engage with the user. 

If you’ve ever audited your WordPress site through GTmetrix or PageSpeed Insights, you’ve probably come across the suggestion to “defer parsing of Javascript”:

Eliminate render-blocking resources by deferring non-critical JS - Source: GTmetrix
Eliminate render-blocking resources by deferring non-critical JS – Source: GTmetrix

In plain English, it means that some Javascript is affecting your site loading time — and that you should do something to improve speed. 

In this tutorial, you’ll learn everything you need to know about deferring Javascript and why it’s crucial for the performance of your WordPress site. Because deferring JavaScript can be daunting at first, we’ll share some easy optimization techniques you can implement for your site. 

What Does Defer Parsing of JavaScript Mean?

Defer Parsing of Javascript means to delay the JS processing that is not needed immediately on the visitor’s screen. Deferring Javascript is a key optimization technique to minimize your main thread work and remove useless weight during the page load. 

What Do Defer and Parsing Mean in Javascript

When you defer Javascript, here’s what happens: you postpone or delay the loading of Javascript to load the most important content first. You tell the browser not to process (parse) a part of the Javascript just yet. Instead, the actual page content will get the loading priority over the JS code that must be executed immediately. 

📖  To keep in mind:

Defer = to load at a later time or postpone a part of the code

Parsing = the process of “reading” and “understanding” the code by the browser

JS usual path = Download > Parse > Compile > Execute > Render on the visitor’s screen

Defer Parsing of Javascript to Reduce Blocking of Page Rendering

The render-blocking resources are stylesheets, Javascripts, and HTML that delay or block the browser from displaying the page content to the visitor. Defer Parsing Javascript is one of the strategies to eliminate render-blocking resources because the browser will know which lines of code need to be loaded in priority. 

Let me show you how render-blocking resources affect browsers and the loading time with a code snippet with HTML and JS: 

How render-blocking resources affect browsers
How render-blocking resources affect browsers

This is what is happening for my browser behind the scene: 

  1. My browser sees that some HTML needs to be downloaded.
  2. But then, he finds some JS to parse and execute. The browser can’t execute everything at the same time: the download of my HTML (actual content) is paused.
  3. Performance issue triggered: while my browser is processing the <script.js>, the rest of my HTML is blocked. Consequently, rendering the page content to the visitor takes more time. 

What changes if you defer parsing of JS?

When you defer parsing of JavaScript, you tell the browser to load and parse the JavaScript file separately. The DOM – or the critical content – will be shown to the visitors immediately instead of being blocked, like in our above example.

Why Defer Loading of Javascript is Important for Performance

Deferring loading of Javascript will significantly reduce the render time of your page and improve your performance. But why? 

Remember that the browser must go through the contents of all <script> tags to load a page. The more scripts you have to process, the more page loading will increase.

Consequently, if you delay some of the Javascripts, your browser will be able to focus on the most important: render the content being viewed by the visitor as fast as possible. 

To achieve this outstanding performance, your browser needs to prioritize the most critical code to achieve this outstanding performance. As a result, any actions towards Javascript code optimization and prioritization will:

Let’s give an overview of each benefit you get by deferring the parsing of JavaScript.

Improve Overall Core Web Vital Scores and Lighthouse Performance Grade

You may have heard of the Google Page Experience that includes the Core Web Vitals as a ranking factor.

SEO, user experience, and performance - Source: WebDev
SEO, user experience, and performance – Source: WebDev

Google says that providing great content is not enough anymore: you also need to take care of the loading time, the perceived speed from a user perspective, the overall interactivity, and the stability of the page. 

To measure and optimize your Core Web Vitals, you can use Lighthouse, an open-source tool for measuring the quality of a web page. 

Optimize First Input Delay (FID)

When you defer parsing of JS, you also optimize your First Input Delay metric (one of the Core Web Vitals). Why? First Input Delay calculates how long it takes for the browser to respond to the first user’s activity on the page (e.g., clicking on a link or tapping a button). If the browser is too busy dealing with large JavaScript files, it just can’t process the requests coming from the user. By deferring the JS, the FID metric has more chance to be in the green. 

Optimize Largest Contentful Paint (LCP)

When you defer parsing JS, you’ll also optimize the Largest Contentful Paint metric (which is also a Core Web Vitals). It measures how long it takes for the largest element to become visible by the user. LCP content is often the most important part of a website, such as its hero header image or the title:

Largest Contentful Paint - Source: CNN
Largest Contentful Paint – Source: CNN

This content contributes to the user’s first impression of a website: if the main image takes a long time to load, then the whole website will be seen as slow. On top of that, a fast LCP also helps reassure the user that the page will be useful.

To ensure a good LCP score, you also need to ensure that your server response time is short. You can do this by telling your browser to load its largest content first before dealing with any other JS files. Does this method sound familiar? This is called deferring parsing of Javascript.

Optimize First Contentful Paint (FCP)

The First Contentful Paint (FCP) is a user-centric metric for measuring the perceived page load speed.  Google suggests deferring non-critical resources to ensure that the first piece of content is loaded as soon as possible.  

The figure below shows what happens if the JS is not deferred and some JS is blocking the execution of my content (FCP):

First Contentful Paint will be delayed if some JS is found during the execution - Source: GTmetrix
First Contentful Paint will be delayed if some JS is found during the execution – Source: GTmetrix

Eliminate Render-blocking Resources 

Lighthouse flags all the scripts and stylesheets blocking the first paint of your page. The goal is to reduce the impact of these render-blocking content on performance by inlining critical resources, deferring non-critical ones, and removing unused code. 

Important: how to identify what is critical content and what is not? 

You can audit your page through the Coverage tab in DevTools. Here’s how to read the report: 

  • Green (critical): scripts are needed for first paint 
  • Red (non-critical): scripts that are not being in the viewport
Identifying critical vs non-critical resources - Source: WebDev
Identifying critical vs non-critical resources – Source: WebDev

Conclusion: to deliver the optimal performance you should defer any JavaScript that is below the fold. This will also reduce Javascript execution time and optimize the critical rendering path rendering the actual content to the user much faster. 

The Critical Rendering Path is the sequence of steps the browser goes through to convert the HTML, CSS, and JavaScript into the final content on the visitor’s screen. 

Now that we know the benefits of deferring parsing of JavaScript in WordPress, let’s go over several techniques that can eliminate render-blocking JavaScript.

Defer Parsing of JavaScript: the Async and Defer Attributes

To defer parsing Javascript in WordPress, you’ll need to mark the non-critical content with the Async and Defer attributes. They tell the browser to load and parse the JavaScript file separately, so the DOM can be shown immediately.  In other words, you add some interactivity to your Javascript by defining when it should be parsed.

Async vs Defer JavaScript: Which One Should You Use?

Async and Defer have both have one common goal: to allow users to see the HTML content faster.  Wondering if you should use async or defer? Here’s the difference you should keep in mind. Defer is used for scripts that need the whole DOM and does not execute until everything you really need is ready. Async is used for independent scripts, like counters or ads – it’s downloaded in parallel and executed as soon as it’s available.

Let’s go over each attribute: 

  • Async script: downloads JavaScript while still parsing HTML but then pauses the HTML parsing to execute the JavaScript. It can interrupt the page rendering to execute as soon as possible in no particular order. 
Async attribute
Async attribute

Example of a script tag with the async attribute: 

<script src='http://yoursitehere.com/js/scripts.js' async='async' type='text/javascript'></script>

When using Async? ​​For very high-priority JavaScript resources that should run as early as possible in the loading process.

  • Defer script: downloads JavaScript while still parsing HTML and waits to execute it until after HTML parsing is finished. It won’t interrupt page rendering to execute, and the execution is done in sequence just before the DOMContentLoaded event. 
Defer attribute
Defer attribute

Example of a script tag with the defer attribute: 

<script src='http://yoursitehere.com/js/scripts.js' defer='defer' type='text/javascript'></script>

When Using Defer? General JavaScript resources that aren’t critical to the initial rendering of the page can be run later in the loading process.

Page Speed Checklist gives a very clear overview of both attributes in the table below:

async vs defer - Source: Pagespeedchecklist
async vs defer – Source: Pagespeedchecklist
Async doesn’t mind whether the DOM is fully loaded, whereas Defer waits for the DOM to be loaded before it executes.

In the next part, we will see two ways to defer the parsing of JavaScript in WordPress – with or without the help of plugins. 

How to Defer Javascript Manually

Here are two ways to defer parsing of JavaScript manually.

Defer Javascript Manually Via Your functions.php File

Here’s a short tutorial to add the defer attributes to render-blocking JS using your functions.php file. 

  • Go to Appearance > Theme Editor and open your functions.php file 
functions.php file in WordPress
functions.php file in WordPress
  • Add the following code snippet:
function defer_parsing_of_js ( $url ) {
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 );

Defer Javascript with Rocket Loader

The second method to defer parsing of JavaScript is to use Cloudflare Rocket Loader that prioritizes your actual website’s content (text, images etc) by deferring the loading of the JS. Your JS will be parsed after rendering your web page, not before. 

Rocket Loader can be enabled directly from your Cloudflare Dashboard:

  1. Go to the Speed app > Optimizations.
  2. Scroll down to Rocket Loader to enable it.

If you feel overwhelmed by the attributes and by editing your functions.php file, there are several plugins that offer to defer parsing of JavaScript in WordPress. We’ll go over them in the next section. 

How to Defer Javascript With a WordPress Plugin (The Easy Way)

Almost any other optimization plugins can be used but we have selected 4 popular WordPress extensions that will defer parsing of Javascript in WordPress, namely:

  • WP Rocket offers the powerful “Load JavaScript deferred” option. The defer attribute will be applied to all the JavaScript files on your page.

Here’s what happens when this option is activated: 

Loading Javascript deferred with WP Rocket
Loading Javascript deferred with WP Rocket 

WP Rocket adds the defer attribute for you:

Defer attributes automatically added by WP Rocket
Defer attributes automatically added by WP Rocket
  • Async JavaScript gives you full control of which scripts to add an ‘async’ or ‘defer’ attribute to increase the performance of your WordPress website.

You can enable async or defer automatically on all your scripts: 

Enabling async JS in one click - Source: Async JS
Enabling async JS in one click – Source: Async JS

Or you can apply the attribute to each script manually:

Manually adding Async on each script- Source: Async JS
Manually adding Async on each script- Source: Async JS
  • Asset Clean Up defers combined JavaScript files by applying “defer” attribute to the script tags. 
Deferring JS with Asset clean-up
Deferring JS with Asset clean-up 
  • Autoptimize also offers the option to defer parsing your scripts.

In the plugin’s settings page, check the “Individual JS files will be minified and deferred” box. Your non-essential scripts will be deferred.

Deferring JS with Autoptimize
Deferring JS with Autoptimize

How to Load Javascript only on Specific Page in WordPress (with a Plugin)

⚠️ Some scripts should not be necessarily deferred or you may want to load JS only on a specific page. 

WP Rocket has the largest automatic exclusions for JavaScript deferring than any other performance plugins. It allows you to exclude a single file, a group of files, an externally hosted file, and even a minified file. 

You can also add any exclusion manually and use a dedicated field in the settings to exclude some URLs of JavaScript files:

Possibility to exclude an URL when deferring JS- Source: WP Rocket
Possibility to exclude an URL when deferring JS- Source: WP Rocket

How Deferring Parsing of Javascript Makes Your Site Faster

For this section, I’m going to use Lighthouse to conduct a performance audit on my mobile site.

If you are not too familiar with Lighthouse, you should read our full guide about improving the Lighthouse performance score on WordPress. 

I’ll compare my page speed before vs after deferring the parsing of Javascript. 

To defer parsing of JS, I’ll use WP Rocket — one of the best cache and performance plugins available on the market.

  • I’ll also check which Javascript warnings are flagged by PageSpeed before and after the optimization.

Let’s get to the data!

#1 Performance Test without WP Rocket

Without WP Rocket, my overall grade is 43/100 – putting my performance in the red according to Lighthouse. 

One of my Core Web Vitals is in very bad shape: the Largest Contentful paint is 14.2 s! The Time to Interactive is high (13.4 s), and the same goes for the Speed Index (12.0 s). 

Defer parsing of JS not enabled - Source: PageSpeed
Defer parsing of JS not enabled – Source: PageSpeed

On top of that, PageSpeed flagged several JS-related issues, as you can see in the figure below: 

Issues that could be solved by deferring parsing of JS - Source: PageSpeed
Issues that could be solved by deferring parsing of JS – Source: PageSpeed
Note: To improve performance, you may also consider removing unused JavaScript and minifying it. Anything towards the optimization of your Javascript will be beneficial for page speed optimization

#2 🚀 Performance Test with WP Rocket + “Load JS deferred” Option Activated 

I’ve now activated WP Rocket and checked the “Load JavaScript deferred“ option available from the files optimization tab:

“Load JavaScript deferred“ in one click with WP Rocket
“Load JavaScript deferred“ in one click with WP Rocket

Thanks to WP Rocket, my overall grade is now green. I’m scoring a 99/100 score on mobile. All my Core Web Vitals are in good shape, and the rest of my metrics have significantly improved:

Deferring parsing of JS with WP Rocket - Source: PageSpeed
Deferring parsing of JS with WP Rocket – Source: PageSpeed

The passed audit section also looks much better, and WP Rocket fixed the JS-related issues on PageSpeed: 

Passed audits by deferring parsing of JS with WP Rocket - Source: PageSpeed
Passed audits by deferring parsing of JS with WP Rocket – Source: PageSpeed

Wrapping up

In conclusion, there are two ways to defer parsing of Javascript in WordPress:

  • Adding the defer or async attribute manually into your script tags
  • Use a WordPress plugin 

As a reminder, the WP Rocket plugin added the defer script automatically on the critical content and allowed us to pass the Lighthouse performance audit: 

Performance without WP Rocket
(JS parsing is not deferred) 
🚀 Performance when WP Rocket defers parsing of JS

A last piece of advice would be to always check the front end of your site after using the defer tag manually or via any of the WordPress plugins. The goal is to make sure that deferring certain scripts hasn’t broken the above-the-fold content. 

Reminder: what to do if a JavaScript script is broken after deferring it?

Answer: simply add the script you want to exclude from deferring in the following WP Rocket settings:

Loading Javascript only on a specific page with WP Rocket
Loading Javascript only on a specific page with WP Rocket

🚀 WP Rocket is one of the best plugins to defer parsing of Javascript in WordPress. If you don’t feel like editing your functions.php file or adding any extra code, then let WP Rocket do the job for you. No risks taken: you are covered by the money-back guarantee within 14 days of purchase. 


Comments (6)

Maybe you could consider to build in a function which lists all js and css files and allow a file-by-file selection of load order and load-type.

Cheers
Hansjörg

I am on SiteGround so I use their SG Optimizer with WP Rocket, but sometimes I have to use one or the other. Would it be better to just use Rocket?

I am using WP Rocket and followed the steps above. I'm still in the red on GTMetrix with no improvement. Do you have some troubleshooting suggestions?

Hi guys!

After selecting "load Javascript deferred", my source code shows something like

so there's no "defer".

I presume that's because I added async='async' to the tag in some previous attempt to speed things up?

Is that correct and -if so- would you recommend removing async='async' from the tag?

Thank you!

Latest Articles of Page speed and caching
Subscribe to Our Newsletter

Stay in the loop with the latest WordPress and web performance updates.
Straight to your inbox every two weeks.

Get a Faster Website
in a Few Clicks

Setup Takes 3 Minutes Flat
Get WP Rocket Now