How To Defer Javascript in WordPress & 6 Other SIMPLE JS Optimization Techniques

How to defer Javascript in WordPress
How to defer Javascript in WordPress

Deferring Javascript is a powerful way to improve your site speed. 

Most articles around the web give you super long explanations of how to defer Javascript in WordPress, which you probably don’t want to read. Plus, most of it is just rewritten nonsense and filler content authored by writers who’ve never optimized a site in their life.

We’ve optimized 4000+ sites over at WPSpeedFix.com, so we have a good deal of experience doing this. 

The two simplest ways to defer Javascript in WordPress are:

  1. Use the WP Rocket plugin which is the most popular site speed optimization plugin for WordPress. Using WP Rocket is probably the easiest and safest way to do it if you’re DIY-ing. Keep in mind that it’s a paid plugin, although still dirt cheap.
  1. Use the Async Javascript plugin which is free, but a bit more complicated to use and more buggy. In other words, it’s more likely things will break.

We’ve detailed how to configure both plugins below, as well as how to make sure you haven’t broken anything in the process, which is common when messing with optimizations like this.

Note that there are other plugins we use in edge cases like PerfMatters and Asset Cleanup Pro, but these are even more complex and we typically only use them for more advanced optimizations.

Deferring Javascript is only one way of optimizing your site for speed. When you defer it, Javascript executes and does its processing AFTER most of the site rendering is complete. For the most part, it makes Javascript non-render blocking – you may come here after seeing an error or warning like “remove render blocking javascript” or something similar.

Executing the Javascript later allows the web browser to use CPU power for displaying the site instead of doing things like executing Google Analytics scripts or Facebook marketing code which can be done later in the load process. The end result is faster page load or faster perceived page load.

We’ll explain the difference between the Javascript attributes async and defer further down in this article. If you’re reading this, I’m guessing you probably care more about site speed, so we’ve provided 6 other methods for optimizing Javascript that go well beyond simply deferring it.

How to Defer Javascript in WordPress Using WP Rocket (easiest + safest, paid plugin)

WP Rocket's landing page - how to defer Javascript in WordPress

WP Rocket is our favorite plugin for deferring Javascript. It allows you to delay the loading of JS files until the user actually interacts with them, which significantly reduces the load time of your page when a visitor first opens it.

WP Rocket is very easy to use, and you won’t need to mess around with any code to get it done. Although it’s a paid plugin, it’s dirt cheap and well worth the tools it delivers. In addition to deferring Javascript, this plugin offers other site optimization features, as well.

Once you’ve installed the plugin to your WordPress dashboard, here’s how to defer Javascript using WP Rocket on your WordPress website:

  1. Open the WP Rocket dashboard.
  2. Go to the File Optimization tab.
  3. Find the JavaScript files section.
  4. Click on the check box where it says Load JavaScript deferred.
  5. It’s also a good idea to make sure that Safe Mode for jQuery is enabled, too. On newer version of the plugin, Jquery is excluded using a URL string instead of a checkbox.
  6. Click on Save Changes. You’re done!
Defer Javascript in WP Rocket

How to Defer Javascript in WordPress Using Async Javascript (more technical + risky, free plugin)

Async Javascript is a free WordPress plugin. However, it is a bit more technical and more prone to bugs – as free plugins often are.

With Async Javascript, you have the option to either async or defer the parsing of Javascript, a difference that we’ll explain in greater detail at the end of the article. In most cases, however, you’ll probably need to use async rather than defer. Defer is recommended if the script is reliant upon another script file on the page.

Regardless of which parsing method you decide upon, the process of activating it is the same. Once you’ve installed the Async Javascript plugin:

  1. Go to the Async Javascript settings page from your WordPress dashboard.
  2. Click the check box at the top next to Enable Async Javascript? to enable the plugin.
  3. Choose from the table of Quick Settings if you want to apply JS async, JS defer, or if you want to apply either method while excluding jQuery.
  4. In the third section, you can choose whether you want to enable the async or defer JS parsing method.
  5. Click on Save Changes.

Make Sure You Don’t Break Things!

When you’re deferring javascript you’re messing with the load order of files, so there’s a moderate chance something powered by Javascript could break.

We want to avoid deferring jQuery, a Javascript library used heavily on the web, as deferring jQuery files will most likely break them. You’ll see in WP Rocket and other defer plugins options for “exclude jQuery” (as we saw in Async Javascript) or “safe mode for jQuery” (available on WP Rocket). You’ll want to use these options in 99% of cases.

A simple way to see if you’ve broken Javascript is to:

  1. Open your page in Google Chrome.
  2. Right-click anywhere on the website (not on links) and select Inspect from the drop-down menu.
  3. Click on the Console tab.

If you have a look at the screenshot below there’s two Javascript errors (in red), one relating to Jquery.min.js and the other to frontend.min.js.

Usually, the fix when things like this happen would be to exclude those files from being “deferred” which can be easily done in WP Rocket.

troubleshooting javascript errors

You can exclude files in WP Rocket by adding to this text box:

How to exclude files from defer in WP Rocket

How To Optimize Javascript in Other Ways

Optimizing Javascript is not limited to adding WordPress plugins. Here are a couple of other ways you can do it.

Remove it!

This sounds like an obvious solution, but it’s still usually overlooked. Often, we see sites that have installed plugins and third-party Javascript code that hasn’t been used in a long time. Most commonly, this is due to tools like Hotjar or old email marketing tools.

Doing an audit of all the WordPress plugins you’re using, the code in Google Tag Manager and any manual code embeds, and then removing anything not in use can make a huge difference, especially for older sites!

Move Code Further Down the Page or to the Footer

Here’s something neat: the further down the page the Javascript code is inserted, the later in the loading process it runs, and therefore- the less of an effect it’ll have on site speed.

Moving the code for third-party marketing tools like Hotjar, Luckyorange, Callrail, Clickcease, and so forth, from the header of a site to its footer can make a big difference on the site render.

Often we see Javascript inserted right at the absolute start of the code after the opening <head> tag which is not great for speed in most cases. A common offender here is Google Tag Manager code. Even though this code needs to sit in the <head> section of the site, it’s better placed at the bottom of this section right before the closing </head> tag as this means it fires later in the load and render process.

Delay or Pause Javascript Until the User Interacts With the Page

One recently added feature to WP Rocket is the ability to pause or delay Javascript until the user interacts with the site.

This is a fantastic way to squeeze more speed out of the page and it’s perfect for tools like Livechat, Facebook Messenger widgets, or marketing tools like Hotjar – essentially, any code or tools that don’t need to fire until the user interacts with the page are a prime candidate for this optimization.

Move the Code to Google Tag Manager and Use the Window Loaded Trigger

Some third-party code breaks or doesn’t work as expected when you defer it. In that case, we would typically move that embed code to Google Tag Manager and then use the trigger Window Loaded which loads that code only after the page itself has loaded.

There’s three page view trigger types. Typically, “page view” is used, which fires the code immediately. However for most code, using the DOM Ready or Window Loaded trigger is better for site speed.

This Google article gives a short explanation of each type of trigger.

The image below is from an article (https://pavelbrecik.cz/the-easiest-cro-you-can-do-is-via-google-tag-manager.html ) detailing GTM triggers and their image on site speed and is a great visual representation of when the different triggers fire:

Use Cloudflare Rocket Loader

Cloudflare Rocket Loader is an even more advanced way to defer Javascript and it can squeeze even more speed out of a page in addition to using WP Rocket for deferring Javascript. The combination of the two usually works better than either of them as standalone optimizations.

Rocket Loader is simple to enable. All you need to do is turn it on under the Speed tab in Cloudflare. 

IMPORTANT NOTE: The Cloudflare Rocket Loader is much more aggressive than WP Rocket, so it’s also more likely to break things, especially for JS-heavy sites like WooCommerce. Make sure you check the Console tab for errors as we discussed earlier.

For sites where we can’t enable the Rocket Loader sitewide (due to it breaking things like the checkout), we’ll often add a page rule to enable it just on the homepage or on the top 5-10 pages, where it’s reasonable to check them all manually. 

Use Browser Hints To Speed Up The Code – Preconnect & Preload

“Browser hints” are HTML code that tells the browser to do certain things. In this case, the preload directive tells the browser to load particular files earlier in the load process. The preconnect directive tells the browser to do a DNS lookup and connect to a server address.

We can use both directives to speed up Javascript and site speed, as they get the browser started on tasks like DNS lookups that can often be slow.

99% of the time we only use the preconnect directive and will typically add https://www.googletagmanager.com, https://www.google.com and hostnames for other marketing scripts as preconnect directives.

A lazy way to do this is using the Pre Party Resource Hints plugin on WordPress.

On the other hand, a more effective way would be to use a speed test tool (e.g. Site Speed Bot) and review the waterfall for slower third-party code. Here’s a good example:

Using Preconnect to speed up Javascript

Typically, we’ll add preconnect code manually or use a plugin like Perfmatters to do it for us.

If we were going the manual route, we’d insert this code into the header of the site

<link rel=”preconnect” href=”https://plausible.io”>

Peconnect in Prefmatters

Combining and Minifying Javascript Can Sometimes Help, but Not Always

Wherever you see Javascript and CSS optimizations mentioned, you’ll see recommendations to minify and combine these files.

On the modern web, most text files like JS and CSS are either minified already or are in the process of being minified by a CDN service. Typically, when we’re using Cloudflare, for instance, we’ll have it do the minification. In any case where the server is using Gzip and Brotli (most do) minify does next nothing for site speed.

So, combining Javascript files *can* help sometimes, but not always. If you’re optimizing right to the edge, it’d be worth testing combined vs uncombined JS to see which is faster.

Defer vs Async Attributes

The Javascript async and defer attributes are really poorly understood across the web. So often we see companies claim their embed code is optimized because the code has async tags, but oftentimes, that’s not really the case.

The graphic below from this excellent article explains the difference between async and defer.

Difference between async and defer attributes

In simple terms:

No JS attribute means the processing, or parsing of the page stops to download and execute the Javascript, making it heavily render blocking

Async tags partially optimize the Javascript by blocking the rendering when the Javascript has downloads

Defer tags fully optimize the Javascript waiting until the HTML has been fully processed, and then execute the Javascript. You’ll note that the JS still downloads during the HTML processing phase even when it’s deferred. This means that it’s still for the best to put the JS as far down the page as you can, so that it will have the least impact on the site render speed.

Leave A Response

* Denotes Required Field