As somebody who is trying to understand how to defer parsing of Javascript, we believe you have a problem. You own or have visited a website of somebody you know (maybe a client?) and it takes forever to load. And when you ran it through website speed testing tools, you got a recommendation which you're not sure how to implement.
In this article, we're going to share several ways of how to defer Javascript and fix this warning and ultimately, make the website load faster, without throwing this error!
If you're short on time, here are some quick actions you can do:
Instructions for How To Defer Parsing of JavaScript
- Download the Async plugin here.
- Click on Plugins > Add New > Upload plugin and select the file you have just downloaded.
- Click on Activate of the installed plugin.
- Go to Plugins and click on Settings for the Async plugin you have just installed.
- Clicking on Enable Async Javascript, or Apply Async as two of the most common ways to apply the fix.
- Test your website, to see that everything is still working well.
Why is the procedure to implement defer parsing of Javascript important? If you don't defer parsing of Javascript, your website will seem like it is loading slowly. Javascript is essentially an important building block in the language of the web, it allows web developers to create "dynamic" functionality.
However, in most cases, Javascript files tend to get quite large. They also might pull in from 3rd party servers. This makes the download slow. But this is only half the problem.
The biggest problem is that if there is no defer parsing of Javascript, the browser is BLOCKED from showing content. The website DOES NOT RENDER. And what does this look like to a user? It looks like the site is either slow, broken, or completely dead.
The problem is compounded on mobile devices, where the processing power available, together with the bandwidth available make the experience feel even worse.
And what will the users who get such an experience do? They will bounce away from your website, never to return!
If you've been around the web industry for a while and you’re trying to improve your website’s SEO, you already know that website performance is crucial in improving your search engine visibility.
And if you’ve used Google PageSpeed Insights to check your website, besides "defer parsing of Javascript" there are even more cryptic warnings, such as the one which says “Eliminate render-blocking resources”.
This technical stuff seems to have the biggest impact on your load speed!
Eliminate?! But how am I supposed to eliminate these crucial files from my website?
Don't worry, we're here to help you fix these warnings, resolve these issues and ultimately making your pages load faster!
Because you don’t have to remove them. All you have to do is to defer parsing of JavaScript.
Have a look at this short video below to see how simple it is to defer parsing of Javascript using one of the methods below:
In non-geekspeak, what this means is that you need to tweak a few things in your WordPress, to allow the page to let your content load first before loading or parsing your JavaScript files.
This is because, if you do not defer parsing of Javascript, rendering the website becomes a very heavy operation, and as we said above, the website will look like it's broken.
To ensure that the user stays on the site, we would like to let them know that something is actually happening, and show content to the user, instead of waiting for the browser to do all the heavy-lifting before actually showing anything to the user.
Incidentally, if you are looking to make your WordPress fast, there are a few plugins such as this one that can make a real difference in performance in a few minutes (with little to zero effort).
If you're interested, WP Rocket can setup defer parsing of Javascript and many other tweaks to make your site faster, just click on the banner below to check it out.
Not ready to use a plugin for now? Read on...
What is Defer Parsing of JavaScript?
Defer parsing of Javascript means using "defer
" or "async
" to avoid render blocking of a page. This HTML command instructs the browser to execute/parse the scripts after (defer) or asynchronously (in parallel) to the page loading. This allows the content to show without waiting for the scripts to be loaded.
By setting up defer parsing of JavaScript, you will be able to let your content load faster and with high priority.
Why is that?
See below this excellent explainer demonstrating how web pages are loaded and how JavaScript files are greatly hampering your website’s loading time.
Continuing on the video above, let’s take a brief look at what happens when someone visits your website:
- When a user clicks a link pointing to your website, the user’s browser will request it from your server, which your server will then “serve” to your user’s browser.
- The user’s browser then receives and sees the HTML content of your webpage and will start rendering it. It will start building your webpage from top to bottom.
- If it finds JavaScript files along the way, the browser will stop and fetch it (if it’s an external file), then parse it
- Only after fully fetching and parsing every single script will it continue to load the rest of your content.
You're probably already starting to see where the problem lies.
When your pages have a lot of JavaScript files, it can massively impact your website’s loading time - negatively.
Your user’s browser will continuously show the loading icon or spinning wheel while parsing and loading your scripts before it shows your actual content - this especially visible on mobile browsers or users on low-speed data connections.
If it takes more than a few seconds especially if you are serving your scripts from an external server (and that server happens to have problems at the moment) - your visitors will start getting edgy.
During that time, your user sees nothing but a white blank page. Isn’t that one of the most frustrating things on the internet? Everything is supposed to be instant on the web, why do they have to wait for your page to load?
If a user waits more than 4 seconds, they will start getting edgy. Beyond 8 seconds and your website is as good as dead - the user will bounce away to another website.
You've lost a visitor, and probably their business.
The additional complication is that many times, these JS files are added to your website by essential plugins and themes which you have installed, so you can't exactly get rid of them easily.
So what do you do?
To resolve this, you need to defer parsing of JavaScript. This works by parsing your scripts once the main content has been loaded. Check out the visual below to see exactly the impact in loading time. As we can see the defer command forces the browser to execute the Javascript later, while the async allows stuff to happen in parallel to the download.
Therefore, when a user visits your site, your browser will instead continue parsing everything from top to bottom but skip your JavaScript files for later. This way, your users will be able to see your content immediately without having to wait.
If you’ve watched the video above, you’ve seen that the “async” and “defer” attributes greatly helps.
But how would you do that in WordPress? Also, when is the right time to use them? Let’s see and let’s get started!
Analyze Your Website
Before we begin, you need to know if you have to implement the defer Javascript fix on your site or not. To find out if you need to, you can use several tools that are readily available online.
Some examples are the following:
1. GTMetrix
This one works by checking both PageSpeed and Yslow metrics and gives you a score from F to A. They also give you recommendations as well as tips on how to improve your website if issues are found. It will specifically tell you if you need to defer parsing of JavaScript.
Generally, the score should be at least 71.
The picture below shows a website that doesn’t need deferring.
2. PageSpeed Tools
a tool developed by Google, PageSpeed Insights is another comprehensive tool that provides you with comprehensive information about your site’s performance issues along with tips to fix them just like GTMetrix.
One of the best things about this tool is it includes links to in-depth guides and resources to help you fix all of your performance problems. The picture below shows a website that badly needs to implement defer parsing of JavaScript.
3. Pingdom Tools
Another popular website performance testing tool that’s freely available for everyone.
Although it doesn’t seem to explicitly tell you whether you need to defer parsing of JavaScript, you can check how long it took for your scripts to load thanks to their comprehensive results page.
The image below shows a website that has almost half of its page consisting of JavaScript - a great indicator that you might want to defer your scripts.
4. Varvy PageSpeed
Another excellent tool that will tell you if your site has render-blocking scripts.
What’s best is that it lets you know exactly what they are, just like in the image below:
Okay, cool!
Now you have access to tools that can help you determine whether you need to implement defer parsing of JavaScript files.
But you might be asking why not just implement it and leave it alone? If you defer parsing of JavaScript incorrectly can break things and it can be frustrating to fix if you’re not tech-savvy.
Simply turning on defer mode doesn’t mean that all is set to be forgotten and will work fine. You’ll have to check whether you’ve done it right and make sure everything still works as intended.
For example, if you use jQuery, you have to carefully choose which of your scripts you should defer because there seems to be a problem with defer and jQuery.
In addition to that, you will find that there are tons of questions on Stack Overflow about jQuery, async, and defer which is often about how you should implement defer and async, if you should at all, to your scripts that rely on jQuery.
So, what are the results? Do you need to defer your scripts?
If so, then let’s now find out how to defer JavaScript in WordPress!
How to Defer Parsing of JavaScript in WordPress
Deferring the parsing of JavaScript in WordPress can be fairly straightforward.
You can just install one of the thousands of plugins in the WordPress repository and you’re good to go. But there are also advanced ways of doing it if you need more control, especially if you are using complex scripts to make your site more engaging and interactive.
In this section, we are going to check five different ways of performing defer parsing of JavaScript in WordPress: via plugins, via functions.php, and editing code manually.
There are so many plugins in the WordPress repository that can help you improve your website’s performance.
There are ones that are dedicated to a particular task like minifying your HTML code and there are plugins that try to incorporate all performance-related tweaks in one plugin such as having the ability to minify and defer CSS and JavaScript files, implement and leverage browser caching (which we've covered extensively in this article) and more.
However, not all plugins are created equal. Some work great, some work ok, and some don't work at all and might even break some or all functionality of your site.
(If you'd rather somebody experienced handle this for you, you can get this done using a cheap Fiverr gig by clicking the button below.)
1. Defer Parsing of Javascript using Async Plugin
Honestly speaking, we'd highly suggest opting for a premium plugin (which is dead-cheap) but you are assured of fixing not just this warning, but a whole range of website loading speed problems.
We'll start with one of the most popular ones which are meant to do a single job defined by this article.
One of the most popular choices to perform this job is Async Javascript. This plugin focuses on improving your site’s performance by tweaking how your scripts are loaded and like WP Rocket below, it also comes with additional advanced features that allow you to exclude certain scripts from being deferred.
Here are the steps you need to perform to use this plugin.
- Download the Async plugin here.
- Click on Plugins > Add New in the WP backend.
- Click on Upload plugin and select the file you have just downloaded.
- Alternatively, search for Async Javascript and click Install Now.
- Click on Activate of the installed plugin.
- Go to Plugins and click on Settings for the Async plugin you have just installed.
- We'd suggest clicking on Enable Async Javascript, or Apply Async as two of the most common ways to apply the fix.
- If these do not work, you can try a few different combinations.
- Test your website, to see that everything is still working well.
Perhaps one of its strengths is that apart from the ability to exclude certain scripts from being deferred, you also have the option to choose which scripts to be deferred instead:
You may also notice that you have the option to either async or defer a script. For more information about the difference between the two, you can read this article.
One unique feature of this plugin is that you can specify to exclude a certain theme or plugin.
There’s also an option to integrate GTMetrix on your site so you can always check its performance. Take note that each time you perform a test, however, an API credit will be deducted from your GTMetrix account.
While some people will recommend WP Deferred JavaScript, this plugin has not been updated for more than 3 years and has not been tested with the last 3 major versions, so we highly recommend you don't use this one. It may still work, but it's untested, so it's a risk which you should not take.
If you have a relatively simple site and you are looking to further improve your loading times, then this might be just what you need. This plugin requires no configuration at all - just install, activate and forget.
Again, keep in mind that this one is not recommended for complex sites like e-commerce because of its lack of advanced tweaking options and because of its age. Being able to fine-tune JavaScript deferring options is crucial for large and complex sites.
2. WP Rocket
Currently the leading WordPress performance plugin out there, WP Rocket offers not only the ability to defer parsing of JavaScript files but also your CSS files. In addition to that, you get tons of other performance improvement options.
Some features include the following:
- Minification - shrinks the size of your site’s code so it loads faster. It does so by removing white spaces and other unnecessary characters from the code without affecting its core functionality.
- Concatenation - combines multiple CSS and JavaScript files into one.
- Lazy loading - this is the defer mode for video files and other multimedia content like images. It delays the loading of these resource-intensive files until after the user scrolls down to them.
One of the best things about WP Rocket is that once you install and activate it, you can just leave it alone and you’ll automatically get performance gains.
However, you can configure advanced settings for an even greater performance boost, but keep in mind that some of them might have adverse effects on your site. And because of that, their deferring option for JavaScript and CSS files are not enabled by default because if done carelessly, they can break things.
Thankfully you can exclude certain scripts from being deferred.
You can try excluding all of your scripts first and then defer parsing of Javascript files one by one until you find the problematic one. They have extensive documentation to help you with that. This way, you will be able to maximize performance improvements without breaking or sacrificing some or all of your website’s functionalities.
WP Rocket is a premium plugin, but given the price and functionality provided (not just deferring and asyncing of JS files but plenty of other optimizations that are guaranteed to make your website faster), we believe it's very much worth the price.
3. Speed Booster Pack
Another great, all-in-one performance plugin that allows you to defer parsing of Javascript files is Speed Booster Pack. It’s similar to WP Rocket in terms of features, but it’s free. It has most of the basic features of WP Rocket such as minification, deferring, removing unnecessary files, etc.
Below you can see some of the features available in the plugin:
Under the Advanced Tab, you can choose to exclude some scripts either from being moved to the footer or from being deferred or both. However, you can only add up to 4 excluded scripts, which is certainly a limitation for complex and big sites.
Overall, it’s a good free alternative to WP Rocket, suitable for small sites.
4. Using functions.php tweaks
What if you don’t want to use plugins?
There’s another trick that you can do to defer parsing of Javascript in WordPress and that is by editing your theme’s functions.php file.
Simply copy the code below and paste it at the bottom of your theme’s function.php file:
function defer_parsing_of_javascript ( $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_javascript', 11, 1 );
Do keep in mind that you might mess up your site if you do it wrong, so pay careful attention and make sure you are editing the correct file in the correct theme and that you are pasting the code snippet in the correct location. Be sure to not to delete/change anything else.
Thankfully, you can create a child theme to make safe edits to your functions.php file. In addition to that, if you ever replace or update your theme, you can easily retain all of your custom edits in the file. Here’s a great article explaining how to create a child theme. Once you have created a child theme, just paste the code snippet in the child’s function.php file, save it and it’s all set.
Read More: Message Blocking is Active
5. Tweak Your Code Manually
This might sound scary, especially if you aren’t fond of coding but for advanced users, tweaking the code manually is a great way to defer parsing of JavaScript files in WordPress.
Varvy has a great code snippet that allows your webpage’s initial content to completely load before loading any other external scripts. The code snippet is below:
<script type="text/javascript">
function downloadJSAtOnload() {
var element = document.createElement("script");
element.src = "//www.yourdomain.com/defer.js";
document.body.appendChild(element);
}
if (window.addEventListener)
window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
window.attachEvent("onload", downloadJSAtOnload);
else window.onload = downloadJSAtOnload;
</script>
Replace defer.js with your own script file. Once you’ve edited it to reflect your own script, paste it just before your HTML’s </body> tag. In WordPress, you can do that by editing your theme’s footer.php file.
Again, it is recommended to use a child theme if you were to create edits in your theme files. A little note: editing footer.php through child theme is different from functions.php: you have to copy the entire footer.php of your main theme along with its content to your child theme and then make/add the edits.
If you don’t want to go to the hassle of editing your footer.php, you can use a plugin called Insert Headers and Footers.
Just paste the code snippet in the “Scripts in Footer” box, hit save and you’ll have the script added to the bottom area of your site’s code, above the </body> tag.
And that’s all of the ways you can defer parsing of JavaScript in WordPress! But do they work? Did they improve your site’s performance? Let’s check the results!
Testing the Results
To test the results, go to GTMetrix.com, PageSpeed Insights, and Pingdom Tools to see if your performance grade and loading time improved.
In GTMetrix, your score should be at least 71. The more the better! A perfect score would like this :-)
In PageSpeed Insights, look for “first paints”:
Generally, when you are testing if your implementation of defer parsing of JavaScript has resulted in the scripts getting deferred, aim for green results in First Contentful Paint and First Meaningful Paint.
Compare before and after deferring and check if they improve.
For Pingdom Tools, take a look in the load order section and see if most, if not all, of your script files are loaded last. Compare before and after deferring and watch out whether script files changed position in the load order (i.e. did they load earlier or later on).
Did the results satisfy you? If so, great job! If not, try experimenting more. If you used other methods on our list, try using advanced plugins that allow you to further customize your deferring and performance options. Furthermore, check out some recommendations from Google in the next section. They might help you.
How to Defer Parsing of JavaScript Using A Script
There are different techniques you can use to defer parsing of JavaScript. The next section discusses what you need to do.
In summary, you need to perform the following:
- Copy the code below and add it just before the </body> tag in your HTML.
- Replace example.js in the code below with the file containing the script to be deferred.
- Save the changes.
- Test your website to see the effect.
Let's look at these steps in some more detail:
-
Use a script to call an external JS file once the initial page is done loading. On varvy.com, Patrick Sexton suggests a method that allows the website content to load, before loading a JS (to ensure that the user can see the content first). This ensures that the critical loading path is not affected by scripts that cause any render-blocking. The method involves creating an external file that is not required for displaying the content initially. By then adding the following script just before the </body> in the HTML. The following example uses a file example.js, which would need to be updated accordingly.
<script type="text/javascript"> function downloadJSAtOnload() { var element = document.createElement("script"); element.src = "example.js"; document.body.appendChild(element); } if (window.addEventListener) window.addEventListener("load", downloadJSAtOnload, false); else if (window.attachEvent) window.attachEvent("onload", downloadJSAtOnload); else window.onload = downloadJSAtOnload; </script>
Once the webpage finishes loading, the script will begin downloading and executing example.js - the problem is that you'll need to create the file manually.
-
Using the async or defer attributes. The JS tag async or defer attributes act in a similar way - the way they work is such that they minimize the amount of time where HTML parsing stops to wait for the downloading and executing of scripts. Async allows the downloading of JS files to occur asynchronously, rather than synchronously, i.e. a new thread is opened to download while HTML continues to parse. Defer instructs the browser to execute the script AFTER the page loading has completed. This is another way to allow the page parsing to complete and thus not creating an impact on loading time. Both of these tags minimize the render-blocking of JS. In the usage of both of these, the JS does not need to wait for the HTML to finish parsing before starting to download or execute - which ensures that the page still loads quickly. See how the execution happens for async and defer respectively in the images below.
-
Move JavaScript to the bottom of your page. The 3rd and final suggestion is to move any
<script>
tags to the bottom of the pages (especially if they are not critical, such as ads). This method is not ideal, because the browser will still be busy until the last script has completely downloaded and been parsed. Given that the browser seems busy, some visitors may not engage with the page until it is completely loaded, resulting in a potentially negative user experience.
Suggestions from Google
Google has tons of resources for improving your website’s performance. They even have a page dedicated to improving your site’s script loading time, which you can check here.
On the left menu, you can also find other resources that help you improve your site’s performance. Make sure you also check them out if your PageSpeed Insights report reported problems related to them.
For an overview, Google suggests that you should inline critical scripts instead and either async or defer non-critical scripts. That means scripts that are required by your site should be embedded in the HTML instead. That is, however, the job of WordPress theme and plugin developers - but if you were to create your theme or plugin, keep this in mind.
Read More: How to hire (GREAT) Javascript developers
In addition to that, Google also outlined a way for you to manually identify which of your scripts blocks the rendering of your webpage by having a very long loading time. You can do that by utilizing Chrome’s Dev Tools’ coverage tab.
Defer Unused CSS
A similar problem that you might see occurring these days, also in the Pagespeed insights tool, is the Defer of Unused CSS. While this is a similar problem, it's roots are somewhat different. Essentially, the CSS would need to be restructured to fix this correctly.
{loadpostion imh-embed}
Frequently Asked Questions
How do I fix defer parsing of JavaScript in WordPress?
To fix the defer parsing of Javascript in WordPress you need to do some minor changes to your code. You can either find all scripts and add the defer tag to them, or you could install a plugin that does this automatically. You can also create a script that loads the files asynchronously as demonstrated in the How To Defer Parsing of Javascript using a script section of this article.
What is defer JavaScript?
Defer parsing of Javascript is the process of instructing the browser of your website visitors to load specific files to AFTER the page has loaded. This allows the user to see the content of the page much quicker than if you did not implement defer parsing of Javascript
What's the difference between async and defer Javascript?
Async means that the Javascript content is loaded as its own new connection, in parallel to any existing other code. With async, the browser creates a new processing thread that will not slow down any existing downloads while the Javascript is being downloaded and executed. Defer on the other hand, asks the browser to parse the script, after the rest of the content has been downloaded. While this is usually good for speed, there might be some issues with your content, if it references the script that has been deferred (because it won't be available).
How do I minify JavaScript in WordPress?
To minify Javascript in WordPress, you will need to implement a plugin that does this automatically. You can read more about this here.
Wrapping Up
And you just witnessed how to defer parsing of JavaScript in WordPress.
We’ve learned that it can be achieved either via plugins or via manual tweaks. It has tons of benefits for your site such as improved SEO, better user experience and faster loading times. It’s therefore important to ensure that you defer as many scripts as you can for maximum performance gains.
But remember, always keep a backup and test a lot to ensure that you deferred the correct scripts! It might seem tedious but if done right, the benefits and gains are massive.
If you want to really max out your website loading speed, we'd suggest leaving it to the PROs such as the guys from WP Rocket, to get the maximum benefits of this and hundreds of other actions to make your website load faster.
Visit WP Rocket To Make Your Website Faster Today
Please leave a useful comment with your thoughts, then share this on your Facebook group(s) who would find this useful and let's reap the benefits together. Thank you for sharing and being nice!
Disclosure: This page may contain links to external sites for products which we love and wholeheartedly recommend. If you buy products we suggest, we may earn a referral fee. Such fees do not influence our recommendations and we do not accept payments for positive reviews.