[How To] Fix Defer Parsing of Javascript Warning in WordPress

[ad_1]

Defer parsing of javascript wordpress

As somebody who is trying to understand how to defer parsing in Javascript, we believe you have a problem. You own or have visited a website of somebody you know 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 a number of ways of how to fix this warning and ultimately, make the website load faster, without throwing this error!

 

GTMetrix - Defer parsing of javascript warning

Because what will visitors who experience a slow website 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, there are even more cryptic warnings, such as the one which says “Eliminate render-blocking resources”.

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.

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, parsing of Javascript is a heavy operation, and we would like to let the know the user, 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.

What is Deferring of JavaScript?

By deferring your JavaScript, you will be able to let your content load faster and with high priority.

Why is that?

Let’s take a brief look at what happens when someone visits your website: 

  1. 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.
  2. 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.
  3. If it finds JavaScript files along the way, the browser will stop and fetch it (if it’s an external file), then parse it
  4. Only after fully fetching and parsing each and 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 connetions.

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 thing 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.

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. 

See below this excellent explainer demonstrating how web pages are loaded and how JavaScript files are greatly hampering your website’s loading time.

If you’ve watched the video, cool! 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!

How To Defer Parsing of JavaScript

There are several techniques you can use, which can have different levels of effectiveness when it comes to defer parsing of JavaScript. Let’s see an overview of what needs to be done, then we can discuss a number of detailed ways to enable this.

  • Use a script to call an external JS file once the initial page is done loading. On varvy.com, Patrick Sexton, suggests a method which allows the website content to load, before loading an JS (to ensure that the user can see the content first). This ensures that the critical loading path is not affected by scripts which cause any render blocking. The method involves creating an external file which is not required for the 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 minimze the amount of time where HTML parsing stops to wait for the downloading and execturing 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 execure 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 aysnc and defer respectively in the images below.
    async attribute


    defer attribute

  • 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.

Analyze Your Website

Before we begin, you need to know if you have to implement this on your site or not. To find out if you need to, you can use several tools which 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. 

Good defer score on GTMetrix

2. PageSpeed Insights

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 deferring JavaScript.

Gagespeed insights - significant impact on loading time

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 your 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 which has almost half of its page consisting of JavaScript – a great indicator that you might want to defer your scripts. 

Pingdom tools js score

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: 

Render blocking scripts impacting performance

Okay, cool!

Now you have access to tools that can help you determine whether you need to implement deferring parsing of your JavaScript files.

But you might be asking why not just implement it and leave it alone? Deferring JavaScript 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 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 three different ways of deferring JavaScript in WordPress: via plugins, via functions.php, and via 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 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. There are some that work great, some that work fine and some that don’t work at all and might even break some or all functionality of your site. 

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 is 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.

  1. Download the Async plugin here.
  2. Click on Plugins > Add New in the WP backend.
  3. Click on Upload plugin and select the file you have just downloaded.
  4. Alternatively, search for Async Javascript and click Install Now.
  5. Click on Activate of the installed plugin.
  6. Go to Plugins and click on Settings for the Async plugin you have just installed.
  7. We’d suggest clicking on Enable Async Javascript, or Apply Async as two of the most common ways to apply the fix.
  8. If these do not work, you can try a few different combinations.
  9. Test your website, to see that everything is still working well.

async javascript plugin settings

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:

Async javascript exclude

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 in 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.

gtmetrix test

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.

WP deferred javascript plugin

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 your 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 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.

WP rocket render blocking css js

Thankfully you can exclude certain scripts from being deferred.

You can try excluding all of your scripts first and then defer them 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 their price and functionality given (not just deferring and asyncing of JS files but plenty of other optimizations which are guaranteed to make your website faster), we believe it’s very much worth the price.

Download WP Rocket

3. Speed Booster Pack

Another great, all-in-one performance plugin that allows you to defer JS 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: 

Speed booster pack

 

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. 

Speed booster pack limit

Overall, it’s a good free alternative to WP Rocket, suitable for small sites.

Using functions.php Tweaks

What if you don’t want to use plugins?

There’s another trick that you can do to defer JS 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_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 ); 

functions.php edit

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.

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 = “https://cdn.collectiveray.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. 

Insert header and footer

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 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 🙂 

perfect defer score

 

In PageSpeed Insights, look for “first paints”:

Pagespeed insights good score

Generally, when you are testing if your deferred JavaScripts are actually 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.

Suggestions from Google

Google has tons of resource on 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.

google resources

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 own 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 which 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.

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.

 

[ad_2]