How to Defer JavaScript Execution and Improve Loading Times?

People often ask me how to defer JavaScript loading on WordPress sites. It usually comes down to page speed: you want visitors to see the content before the scripts run.

Since WordPress 6.3, you can choose a loading strategy (defer or async) when you’re enqueuing your scripts. That’s the recommended approach for new projects. The manual methods below still come in handy if you’re working with legacy code or need finer control.

A Google search turns up plenty of suggestions. Some work, some don’t. Deferring JavaScript is one of those gray areas in WordPress performance optimization.

I’ll walk you through three proven ways to defer JavaScript on your WordPress site. Caching plugins like WP Rocket handle this automatically, so if you already use one, you may not need to write any code.

Why Defer JavaScript Loading?

JavaScript files load on nearly every page of your site. By default, when the browser reaches a <script> tag, it pauses HTML parsing to fetch and run the script. While it’s doing that, visitors are waiting for the content they came to see.

As a developer, your job is to make sure the critical content loads first. Share buttons, widgets, analytics, and comment scripts can wait.

The idea is to let visitors start reading (that’s usually what they’re there for) and defer script execution until the browser has rendered the content. Google PageSpeed Insights will flag render-blocking scripts as a problem in its Largest Contentful Paint (LCP) measurements.

If you’ve seen warnings like “Defer loading of JavaScript” or “Remove Render-Blocking JavaScript,” I’ll show you what to do about them.

A browser can load scripts in three ways. Which one to use depends on what your script does and what it needs to run.

The diagrams below show the same page in each case. Read them from left to right: the top row shows the browser reading the HTML, the middle row shows it downloading app.js, and the bottom row shows it running the script. The numbers are examples, not measurements.

Default <script>

The browser parses the HTML until it hits a <script> tag. Then it stops parsing, downloads the script, runs it, and picks up where it left off. The striped section in the top row shows that pause. Until app.js finishes running, the browser doesn’t read or show anything below the tag.

<script async>

The browser keeps parsing the HTML while it downloads the script. As soon as the download finishes, the browser pauses parsing to run it. You can’t count on a particular execution order: whichever script finishes downloading first runs first.

The pause in this diagram is much shorter, but it’s still there. When it happens depends on when the download finishes.

<script defer>

Here, too, the browser downloads the script while it parses the HTML. This time, though, it finishes parsing before it runs the script. Unlike async, defer preserves execution order: scripts run in the order they appear in the document.

Look at the top row again. There’s no pause because the browser runs app.js only after it finishes reading the HTML.


How to Defer JavaScript Loading?

Test each change as you go. If adding defer breaks a script, leave that script out. Here are the three main ways to defer JavaScript on a WordPress site:

1. The Modern Way: strategy Parameter (WordPress 6.3+)

If you’re on WordPress 6.3 or later, this is the approach I recommend. Pass a strategy key in the $args array when you enqueue the script:

wp_enqueue_script(
    'my-script',
    get_stylesheet_directory_uri() . '/js/my-script.js',
    array(),
    '1.0.0',
    array(
        'in_footer' => true,
        'strategy'  => 'defer',
    )
);

WordPress checks the dependency tree for you, too. If a script that loads normally depends on a deferred script, WordPress drops defer so the two scripts run in the right order. No hacks needed.

If you want async instead, change 'strategy' => 'defer' to 'strategy' => 'async'.

Starting with WordPress 6.4, core and bundled theme scripts use defer and load in the <head>. That lets the browser discover them earlier. The comment-reply script uses async because comments are a low priority.

2. Defer All Scripts Except jQuery (Legacy Method)

Before WordPress 6.3, a filter in functions.php was a quick way to defer scripts across the board. That filter, script_loader_tag, gives you each finished <script> tag along with its handle. You can use the handle to add defer to every tag except the one for jQuery:

/* Defer every front-end script except jQuery */
function defer_all_but_jquery( $tag, $handle ) {
    if ( is_admin() || str_contains( $tag, ' defer' ) || str_contains( $tag, ' async' ) ) {
        return $tag;
    }
    if ( in_array( $handle, array( 'jquery-core', 'jquery-migrate' ), true ) ) {
        return $tag;
    }
    return str_replace( ' src=', ' defer src=', $tag );
}
add_filter( 'script_loader_tag', 'defer_all_but_jquery', 10, 2 );

jquery-core and jquery-migrate are the handles of the jQuery copy that ships with WordPress. If your theme loads its own jQuery, add its handle to the array on line 6.

Here’s what you’ll see in the page source. The filter leaves jQuery alone, so theme and plugin scripts that need it can still find it:

Once you’ve added the filter, test the site. If a plugin prints inline code that calls a deferred script right away, that code runs before the script loads. The call fails. If that happens, exclude the script’s handle just as you did for jQuery.

Older tutorials used the clean_url filter for this. I did too in an earlier version of this post. That trick no longer works. On current versions of WordPress, it breaks the script’s URL instead of adding defer. If you come across that trick in a functions.php file, remove it.

3. Defer Loading of Scripts by Handle

WordPress 4.1 introduced the script_loader_tag filter. It gives you a cleaner way to control how a script loads based on its handle. If you’re on a pre-6.3 site and can’t use the strategy parameter, this filter is your next best option. On line 2, list the handles of the scripts you want to defer:

function add_defer_attribute($tag, $handle) {
   $scripts_to_defer = array('my-js-handle', 'another-handle');
   if (in_array($handle, $scripts_to_defer, true)) {
      return str_replace(' src', ' defer src', $tag);
   }
   return $tag;
}
add_filter('script_loader_tag', 'add_defer_attribute', 10, 2);

When you register or enqueue the script, its handle is the first value you pass. Here, that’s my-js-handle:

wp_register_script('my-js-handle', $src, $deps, $ver, $in_footer);

To load the script asynchronously, use “async” instead of “defer” on line 4.

Deferring JavaScript with WP Rocket

If you use WP Rocket, you can skip the code above. Go to Settings → WP Rocket → File Optimization and turn on Load JavaScript deferred. WP Rocket adds defer to your site’s scripts, which usually takes care of the “defer parsing of JavaScript” warning.

Two details are worth knowing:

  • Excluded JavaScript Files: If a script breaks after you defer it, enter its URL or a keyword in the field below the option. Give each entry its own line. The guide to excluding scripts from Load JavaScript deferred shows you how to find the right entry.
  • jQuery: WP Rocket can defer jQuery too. When it does, it wraps inline scripts that call jQuery in a DOMContentLoaded listener. That way, those scripts wait until jQuery has loaded. If you exclude jQuery from defer, WP Rocket leaves inline scripts alone.

I’d use the setting or the snippets, not both. If you turn on the setting, remove the snippets above. Then you have just one place to look if a script breaks.

On the same tab, you’ll find Delay JavaScript execution. The name sounds similar, but as I’ll explain next, it does something different. For the other settings on that tab, see the WP Rocket guide.

Defer vs. Delay – What’s the Difference?

Some performance plugins offer “Delay JavaScript” alongside defer. The difference is timing: when does the browser download the script, and when does it run it?

Defer lets the browser download the script while it parses the HTML. The browser waits until it finishes parsing before it runs the script. So the script still runs on every page load, just later.

Delay (sometimes called “lazy load JS”) doesn’t load the script at all until someone scrolls, clicks, or presses a key. That keeps the script out of the initial load path entirely, which can dramatically improve Largest Contentful Paint and Interaction to Next Paint (INP) scores.

There’s a trade-off. Sliders, menus, embeds, and other parts of the page that JavaScript builds may show up late. Some features won’t work until someone interacts with the page. Defer is the safer default for application code. Delay works best for non-essential third-party scripts like analytics, chat widgets, and social embeds.

For YouTube embeds, see the guide to deferring JavaScript for YouTube videos.

Which Method Should You Use?

Here’s how I’d choose:

WordPress 6.3+: Use the strategy parameter when you enqueue a script. It’s the cleanest, most reliable approach.

Pre-6.3 sites: Use the script_loader_tag filter to defer every script except jQuery, or just the scripts with specific handles.

WP Rocket users: Turn on Load JavaScript deferred instead of adding code.

Old clean_url snippets: Remove them. On current versions of WordPress, they break script URLs instead of deferring the scripts.

Non-essential scripts: For analytics, chat, and share buttons, consider lazy loading JavaScript or delaying execution until someone interacts with the page.

You can also preload critical assets to improve the loading waterfall further.

FAQs

Here are a few common questions about deferring JavaScript in WordPress:

Should I use defer or async for WordPress scripts?
Use defer for most WordPress scripts. It preserves execution order and waits until the DOM is ready, which prevents dependency issues. Use async only for independent scripts that don't rely on other code, like analytics or tracking pixels.
Can I defer jQuery in WordPress?
Generally, no. Many WordPress plugins and themes depend on jQuery being available immediately. Deferring it can break inline scripts that call jQuery() or $() before the deferred file loads. The code examples in this guide intentionally leave jQuery out.
Do I need to defer JavaScript if I use a caching plugin?
Most caching plugins like WP Rocket, LiteSpeed Cache, and W3 Total Cache have built-in options to defer or delay JavaScript. If you've enabled those settings, adding manual defer code is redundant and can cause conflicts. Check your plugin's JS optimization settings first.
What is the strategy parameter in WordPress 6.3?
WordPress 6.3 added a strategy key to the $args array in wp_enqueue_script() and wp_register_script(). Set it to 'defer' or 'async' to control script loading natively. WordPress handles the dependency chain automatically, making script_loader_tag filters unnecessary for most cases.
Is the clean_url filter method safe to use?
No. It was always a hack: the clean_url filter was designed for URL sanitization, not for injecting HTML attributes. On current WordPress it no longer works at all, because it breaks the script's URL. Use the strategy parameter (WordPress 6.3+) or the script_loader_tag filter instead.
How do I check if deferring JavaScript actually improved performance?
Run your site through Google PageSpeed Insights before and after the change. Look for improvements in LCP (Largest Contentful Paint) and the render-blocking audit. You can also check the Network tab in Chrome DevTools to confirm scripts have the defer attribute.
Does deferring JavaScript reduce JavaScript execution time?
No. Defer changes when a script runs, not how long it takes to run. The Lighthouse diagnostic "Reduce JavaScript execution time" measures how much time the browser spends parsing, compiling and running each JavaScript file. To bring that number down, give the browser less JavaScript to process: remove scripts you don't need, split large bundles and minify what's left. I cover this diagnostic in Part 2 of the PageSpeed Insights guide.

In Summary

I covered three ways to defer JavaScript in WordPress: the modern strategy parameter, a script_loader_tag filter for everything except jQuery, and that same filter for specific handles. On WordPress 6.3+, I’d use the built-in strategy parameter. If you’re using WP Rocket, turn on Load JavaScript deferred and skip the code.

Deferring scripts is one of the easiest ways to improve performance. Pair it with other WordPress speed optimizations and you can see a noticeable improvement in your Core Web Vitals scores.

Have a question or a different approach that works for you? Let me know in the comments.

Summarize with AI Claude ChatGPT Google AI
Discussion
[  0 Comments  ]

Leave a Comment

To add code, use the buttons below. For instance, click the PHP button to insert PHP code within the shortcode. If you notice any typos, please let us know!