← Tous les articles

async vs defer: loading JavaScript without blocking page rendering (HTML, modules and WordPress)

Blocking scripts, async, defer, type=module and on-demand loading: what each option actually does, which to pick for your own code and third-party tools, and how to apply it cleanly in WordPress.

async vs defer: loading JavaScript without blocking page rendering (HTML, modules and WordPress)

Key points

  • A <script> with no attribute stops the parser: it’s the render-blocking resource Lighthouse and PageSpeed Insights complain about.
  • defer is the right default for your own scripts: parallel download, in-order execution once the HTML is parsed. Keep async for standalone scripts such as analytics or ads.
  • In WordPress 6.3 and later, the strategy argument of wp_enqueue_script() adds these attributes without hacking the HTML, and it respects dependencies.

“Eliminate render-blocking resources” is one of the most common recommendations in PageSpeed Insights reports, and one of the most misunderstood. Someone adds async to everything, the score goes up, and then the carousel fails to start one time in three, or jQuery is not defined shows up in the console. async and defer don’t just affect speed: they change when scripts run and in what order. Here’s how they work, how to choose, and the traps we keep finding when we take over existing sites.

What the browser does with a classic script

The browser reads HTML from top to bottom and builds the page as it goes. When it hits a <script src> without attributes, it stops: downloads the file, runs it, then carries on.

So three blocking scripts in <head> mean three downloads and three executions before a single word appears. On a phone with an average connection, that’s a white screen that lingers.

The old trick was to put scripts just before </body>. It works, since the HTML is parsed first, but the download only starts when the parser reaches the end of the page, which is late. The modern attributes do better. Here are the variants side by side:

<head>
  <!-- Blocking: the parser stops while the file downloads and runs -->
  <script src="/js/legacy-script.js"></script>

  <!-- defer: downloaded in parallel, run in order once the HTML has been parsed -->
  <script defer src="/js/vendor/carousel.js"></script>
  <script defer src="/js/main.js"></script>

  <!-- async: runs as soon as it arrives, no order guaranteed (independent scripts) -->
  <script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXX"></script>

  <!-- Module: deferred by default, like defer -->
  <script type="module" src="/js/app.js"></script>
</head>

defer, async, module: how to choose

defer: the script downloads while the HTML is parsed and runs once the whole document has been read, just before DOMContentLoaded. Deferred scripts run in the order they appear. That’s what you want for nearly all site code: the DOM is complete, and a library declared before the code using it is ready in time.

async: the script downloads in parallel and runs as soon as it arrives, even mid-parse, with no ordering guarantee at all. Ideal for a script that depends on nothing and that nothing depends on: analytics, an ad pixel, a third-party A/B testing tool. A bad idea for a library plus the code that uses it: depending on which arrives first, the second will sometimes run before the first.

type="module": modules are deferred by default. Adding defer does nothing; adding async makes the module run as soon as it arrives.

Two details catch people out. async and defer have no effect on a classic inline script (one without src): it runs exactly where it sits. And when both attributes are present, current browsers apply async.

Our rule on projects: defer for site code and its libraries, async for self-contained third-party tools, and no blocking scripts, except the rare one that genuinely has to act before first paint (say, a tiny inline script that applies the user’s dark theme choice to avoid a flash of the wrong colours).

The traps that break a site after switching to defer or async

Trap number one is an inline script depending on a deferred file. A theme loads jQuery with defer to boost its score, but an inline snippet, added by a plugin or pasted into a widget, calls jQuery(...) halfway down the page. The inline script runs immediately, jQuery isn’t there yet: error. That’s why you never defer a library without first finding out who uses it inline.

The second concerns DOMContentLoaded. A deferred script runs before that event, so a listener registered inside it fires. An async script may arrive afterwards: the event has gone, the listener never runs, and the feature starts only some of the time depending on network speed. The classic “works locally, not in production” bug. The fix is to check the document state:

// Works whether the script is deferred, async or injected later
function whenReady(fn) {
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', fn, { once: true });
  } else {
    fn();
  }
}

whenReady(() => {
  document.querySelectorAll('[data-carousel]').forEach(initCarousel);
});

Finally, ordering between deferred scripts is only guaranteed if they’re all deferred. A blocking script sitting between two deferred ones runs before both, wherever it appears. When you change the strategy of one script in a dependency chain, review the whole chain.

In WordPress: the strategy argument, and what to check

Since WordPress 6.3, wp_register_script() and wp_enqueue_script() take an array as their last argument, with a strategy key (defer or async) and an in_footer key:

<?php
add_action( 'wp_enqueue_scripts', function () {
    wp_enqueue_script(
        'theme-main',
        get_theme_file_uri( 'assets/js/main.js' ),
        array(),                          // no blocking dependency (no jQuery)
        wp_get_theme()->get( 'Version' ),
        array(
            'strategy'  => 'defer',       // WordPress 6.3 and later
            'in_footer' => false,         // in <head>: discovered early, run after the HTML
        )
    );
} );

The advantage over the filter is that WordPress takes dependencies into account. If a deferred script is needed by a script that’s still blocking, WordPress falls back to blocking to keep execution order intact. That’s a safeguard, but also a source of confusion: you asked for defer and the HTML doesn’t have it. So always check the generated page (view source, search for the file name) rather than assuming the setting took. Inline scripts attached with wp_add_inline_script() can have the same effect.

jQuery deserves its own note. WordPress loads it as a blocking script in <head>, and many plugins assume it’s available immediately. On our rebuilds, rather than forcing jQuery to defer, we remove the theme’s dependency on it (modern JavaScript does the same jobs without a library): when nothing on a page asks for it, WordPress stops loading it. “Defer all JavaScript” optimisation plugins regularly break forms and carts; if you use one, test every page type and exclude the problem scripts rather than switching everything off.

Going further: don’t load what isn’t used

defer stops scripts blocking rendering, but the file is still downloaded, parsed and executed, keeping the phone’s CPU busy just as the user starts interacting. For heavy tools only some visitors need (chat widget, embedded video, interactive map), the best option is to load them only when they’re wanted:

// Only load the chat widget on the first click of the button
document.querySelector('#open-chat').addEventListener('click', () => {
  const s = document.createElement('script');
  s.src = 'https://widget.example-chat.com/loader.js';
  // Scripts injected this way are async by default; set s.async = false to keep order
  s.onload = () => window.ChatWidget.open();
  document.head.append(s);
}, { once: true });

For your own modules, import() does the same. In WordPress, register a script only on the pages that use it.

To check the outcome, the Performance panel in DevTools shows when each script runs relative to first paint, and Lighthouse lists any requests still blocking. Measure before and after on a mobile profile, and above all confirm everything still works: menus, forms, carts, cookie consent. A higher score bought with a broken form isn’t an improvement.

FAQ

Can I put async on the Google Analytics or Google Tag Manager script?

Yes, Google’s snippets already do: those scripts are built to run independently, with a queue that keeps any calls made before they arrive. Don’t alter their embed code beyond what the documentation describes.

PageSpeed still reports blocking scripts. Why?

Check the page source to confirm the attributes are really there: a blocking dependency, an optimisation plugin or an uncleared cache can cancel your setting. Look at stylesheets too: they also block rendering and are reported under the same recommendation.

A WordPress site that scores poorly on mobile, or breaks as soon as you turn on an optimisation plugin? We audit how your scripts and styles load and fix the cause, not just the score.

Partager LinkedIn Facebook X WhatsApp
</>

webtestudio

Agence web : sites WordPress sur mesure, thèmes premium et logiciels SaaS.

Parler de votre projet →