3 Ways to Defer Parsing of JavaScript on Your WordPress Website
- By Douglas Moore
- Last Updated On April 14, 2020
When a visitor opens your WordPress website, their browser displays its content by fetching it from top to bottom. If it comes across JavaScript, it will stop retrieving the content until it fully loads and parses the JavaScript file on the page. But JavaScript files sometimes take longer to load than simpler content like text or optimized images.
What this means in short, is that JavaScript files can slow down the loading of your website, in turn frustrating your visitors and potentially lowering your SEO rankings.
Now before you start worrying, there’s an easy way to fix this, and it’s by deferring the parsing of JavaScript. We’ll walk you through what it means to defer parsing of JavaScript and how you can do it, both with and without WordPress plugins.
What Does It Mean to Defer Parsing of JavaScript?
First off, let’s note that there’s nothing wrong with using JavaScript. In fact, it’s a great idea! JavaScript files allow your website to have complex features that enhance its look and functionality, therefore improving the user experience. To give you a better idea, keep in mind that every time a web page displays more than static information, like content updates, maps, animated graphics, or live chat, JavaScript is at work.
However, JavaScript files come with a more complex code and the functionalities they offer weigh more than simpler content on your web page. As we mentioned, once the browser reaches the JavaScript, it stops loading the rest of the page until it’s done loading the JavaScript file.
Now, how does this mess with your SEO rankings and frustrate your site visitors? Well, speed is an important factor in Google’s SEO rankings, especially on mobile. As for your website visitors, if your site loads slowly they may simply leave it, and if you’re running an online business this could cost you sales.
So, how can deferring parsing of JavaScript help fix this? To defer parsing of JavaScript basically means to delay the loading, i.e. parsing of JavaScript until the rest of your website’s main content has loaded. Your website will be swiftly displayed in the visitor’s browser, so they’ll be able to view and interact with the page’s content without waiting for the JavaScript file to download. This leaves the JavaScript file to load at the end, once all the lighter content is already up and running. When JavaScript parsing is deferred, it won’t have the same negative impact we talked about in slowing down your web page.
Do You Need to Defer Parsing of JavaScript on Your WordPress Website?
A simple way to figure out if you need to defer parsing of JavaScript – if you haven’t already found this to be the case – is to run your website through a speed testing tool, like Google PageSpeed Insights or GTmetrix. (Maybe you’ve already done this, and that’s why you’re here!) These pages allow you to test the loading speed of your website and figure out what you can do to speed it up.
Once you run your website through a speed testing tool, you’ll get a list of the various factors that may be slowing down your website, such as too many redirects or un-optimized images. One of the high-priority factors that come up is deferring parsing of JavaScript files.
Here’s an example of what this looks like in Google PageSpeed Insights:
Google PageSpeed Insights is a great tool to check the loading speed of your website
In this example, one of the tabs that comes up with suggestions on how you can improve loading time is Reduce JavaScript execution time. PageSpeed Insights has estimated that by deferring parsing of JavaScript, the loading time of the tested website can be reduced by 2.9 seconds – and that’s a lot in loading time. The tool provides you with detailed information on the different URLs and JavaScript files that are slowing down your site, so we recommend you using it.
Here’s another example of running a website through GTmetrix:
GTmetrix estimates how you can improve the loading speed of your website
As you can see, GTmetrix also has a tab labeled Defer parsing of JavaScript. Although the tested website has a high score on this point, GTmetrix still recommends that some further deferring of JavaScript parsing can further improve the page loading speed.
Therefore, run your website through one of these speed testing tools. If you find that your website’s loading time is slow and that the tool recommends you to defer parsing of JavaScript, keep reading this article to find out how you can do just that!
How to Defer JavaScript Parsing in WordPress
There are several methods you can use to defer parsing of JavaScript on your website. In a nutshell, you can do this by either using a plugin or adjusting your site’s script.
The two main attributes you can add to your script to defer parsing of JavaScript are async and defer. These attributes instruct the visitor’s browser to download the JavaScript file without pausing the HTML parsing for the rest of the website. This means that there won’t be any delay in the loading of the main content due to JavaScript.
The main difference between async and defer is in the way they defer JavaScript – async continues to load JavaScript while HTML parsing continues, while defer loads the JavaScript file after everything else has been parsed. We’ll go over more details about the difference between the two in the next section, where we’ll discuss the plugin you can use to add this attribute to your script.
Aside from using plugins, you can also defer parsing of JavaScript is by adding a code to your WordPress theme. This code snippet is provided by Patrick Saxton at Varvy, and we’ll show you how you can do this as well.
The last method we’ll recommend is tweaking your functions.php file. If you’re already familiar with SFTP client, adding a code snippet to the functions.php file will be easy for you!
Before we move on to the guide, we’d like to note that some people put the JavaScript file at the bottom of the page as an easy solution to get the main content downloaded, and delay the JavaScript parsing for the end. However, we don’t recommend this method, because firstly, you may need your JavaScript file to be displayed earlier on in the site, and secondly, because the browser will still detect the website as loading for a longer amount of time.
Without further ado, we present you with the best and easiest ways to defer parsing of JavaScript.
1. The Async JavaScript Plugin
The Async JavaScript plugin is one of the simplest ways to defer parsing of Javascript. This plugin is free, and it gives you the option to choose between the two defer attributes we discussed – async and defer.
The Async JavaScript WordPress Plugin
Before we get into how you can use this plugin, let’s turn back to the difference between these two attributes, so you can decide which one is the better choice for you.
The way a regular script runs is by parsing the HTML file until it reaches the JavaScript file, at which point the parsing will be paused until the file is fetched and executed (downloaded). Here’s a useful chart from Growing with the Web to give you a better idea:
This is how a HTML file is parsed without any added attributes
With the async attribute, the JavaScript file is downloaded during the HTML parsing. So the HTML parsing continues while the script file is being downloaded. Once the JavaScript file is downloaded, the HTML parsing pauses to execute it. Here’s another graph from the same source to better understand the concept:
Refer back to the legend in the previous graph to see how async parsing works
The defer attribute downloads the file during HTML parsing but does not execute the script until the parsing of the website is finished. In other words, the parsing isn’t paused to execute the script like in the case above. Instead, the JavaScript file is executed once the rest of the page is loaded.
With the defer attributed, the script file is executed only once everything else on the page has been loaded
So, which attribute should you use?
In most cases, the async attribute is recommended over the defer attribute. Defer is a better choice in a very few cases – like if the script relies upon or is relied upon another script file.
So back to using our plugin. First, add it to your WordPress plugin library through the plugin’s website or by searching for it from your WordPress admin account.
Once you’ve installed and activated Async JavaScript, go to the plugin’s settings.
The Async JavaScript settings
As you can see from the images, there are some quick and easy settings you can apply to your website’s scripts. Once you’ve enabled the plugin at the top, you can simply click any of the buttons in the second section to easily apply common settings. The third section allows you to choose between the async and defer methods.
The cool thing about Async JavaScript is that it provides you with full control over which scripts you want to defer parsing for. It also allows you to specify the type of attribute (async or defer) for each individual script. You can adjust this in detail by tinkering with the plugin’s additional settings.
An example of how you can specify the attributes for different scripts
There’re also some JavaScript files that you may wish to exclude from the deferred parsing method. This is especially the case with some plugins and themes which rely on jQuery scripts. If you defer their parsing, you may end up messing up the site’s core functionality. For this purpose, Async JavaScript allows you to exclude jQuery scripts from the defer parsing functions.
Your safest bet with jQuery scripts is to exclude them from being deferred
You can also adjust the settings for each of your plugins and themes. Neat, right? You may need to play around with the settings for a while though, so as to see which attributes work best for the different scripts.
2. Add Varvy’s Code Snippet
Patrick Saxton’s method involves pasting Varvy’s code snippet into the HTML file to defer parsing of JavaScript so as to not load the external file that you specify until after the rest of the HTML document has loaded.
Keep in mind that there are two types of JavaScript files – and Saxton makes this quite clear:
- JavaScript files you need in order to keep the page loading properly. This includes things like plugins or themes, which enable core functionality.
- JavaScript files that you don’t immediately need, but do stuff after the page loads. This includes badges in the footer, click events, and so on.
Varvy’s code snippet is appropriate for the second category of JavaScript files – ones that aren’t crucial for the proper functioning of your website. The loading, i.e. parsing and execution of the secondary JavaScript files will begin after the main content has already loaded.
To use this method:
- Open the appropriate HTML file.
- Before the tag, located near the bottom of the HTML file, copy and paste the following code:
function downloadJSAtOnload() {
var element = document.createElement("script");
element.src = "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;
- Replace the part in bold – defer.js – with the name of your external JavaScript file.
- Double check the pathway. Make sure that the JavaScript file you specify exists in the same folder as the HTML file.
And you’re done!
3. Edit Your functions.php File
The last method we’ll look at, which you can use to defer parsing of JavaScript, is editing the code in your functions.php file.
You can access your functions.php file either via SFTP client or directly from WordPress.
- If you’re using SFTP client, go to the WordPress root directory > wp-content > Themes > your current theme > functions.php. Then, download and edit the file, before uploading the updated version back to theme folder.
- If you want to access the file directly from WordPress, go to the WP admin dashboard and select Appearance > Editor. From here, select a theme and click on Select theme to edit from the drop-down menu. Find Theme Functions (functions.php) under Theme Files. Double click. The file will open, so you can edit it and click on Update File once you’re finished.
Paste the following code snippet in your functions.php file to defer parsing of JavaScript:
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 code defers the parsing of JavaScript files on your website, excluding jQuery files so as to prevent the possibility of any core functionalities getting messed up.
While this solution is quick and easy, it does not give you as much control as, for instance, using the Async JavaScript plugin does.
View Related Articles
How To Redirect Your WordPress Site from HTTP to HTTPS
The internet has arguably made a lot of things more convenient for us. From paying bills, to online shopping, academic research, and entertainment – there’s little you can’t do with a computer and an internet connection. However, this also…
3 Ways To Enable GZIP Compression on Your WordPress Site
Since Google’s speed update in July 2018, speed has become an important factor in website rankings on mobile searches. In fact, if you’re running your own website, you probably already know that having a fast-loading website is important both…
JPG vs JPEG: Understanding the Difference
Images are the principal format that communicates content to internet users today. Lots of web optimization techniques are based on the idea that images – the first thing that a potential customer or user sees – is the deciding factor for whether a visitor buys the product and stays on the site or not.