Check 06.13 · Performance and Core Web Vitals

Defer non-essential scripts

Load non-essential scripts after rendering with defer, async or on-demand loading, on WordPress, Shopify, Laravel, Next.js and other platforms.

Priority
Important
Difficulty
Intermediate
Estimated time
1 to 4 h
Free, no account: your progress is saved in this browser.

Ask an AI to check this point on your site

Opens the assistant with a ready-made question: this check, its goal and your site URL.

For Gemini, Copilot or another assistant, copy the question. The link opens the chosen service directly: nothing goes through this site.

In short

A non-essential script is one the page does not need to display its main content: chat, below-the-fold carousel, customer reviews, social sharing, maps, late A/B tests. Deferring it means downloading it without blocking HTML parsing (defer, async, type="module"), or even loading it only when it is needed (idle browser, visible element, click). Once this check is done, no classic script blocks rendering in the <head> any more and the main thread stays available during loading.

Why it matters

When the browser encounters a <script src> tag with no attribute, it stops building the page, downloads the file, executes it, then resumes. Every script placed this way in the <head> delays the first display of everything that follows.

Attributes change this behavior:

Tag Download Execution Order guaranteed
<script src> blocks HTML parsing immediate yes
<script src defer> in parallel after HTML parsing, before DOMContentLoaded yes
<script src async> in parallel as soon as the file arrives no
<script type="module" src> in parallel like defer yes

defer and async have no effect on an inline script (one without src).

Deferring only solves render blocking. A heavy script executed right after HTML parsing still occupies the main thread and delays the response to the first clicks. This is why truly secondary scripts benefit from being loaded even later: when the browser is idle, when the block concerned approaches the viewport, or when the visitor asks for it.

As for search engines, Googlebot executes JavaScript but does not click or scroll the page. Content injected by a script that waits for an interaction will therefore not be seen: only defer this way what brings no content to be indexed.

What it improves

  • First display and LCP (Largest Contentful Paint, the display of the largest visible element): HTML and CSS are no longer held back by secondary scripts.
  • INP (Interaction to Next Paint, the responsiveness to interactions): less JavaScript executed during loading, so fewer long tasks at the time of the first clicks.
  • Lighthouse audit Lower Total Blocking Time, and scripts disappear from the audit on render-blocking resources.
  • Rendering by Googlebot The page is rendered with less work. Indirect effect, noticeable mostly on sites that depend on JavaScript.
  • Rankings Indirect effect, through Core Web Vitals.

How to check

List the external scripts in the initial HTML and their attributes:

curl -s https://example.com/ | grep -o -i -E '<script[^>]*src=[^>]*>'

In the browser console, this command returns the blocking scripts in the <head>:

[...document.querySelectorAll('head script[src]')]
  .filter((s) => !s.defer && !s.async && s.type !== 'module')
  .map((s) => s.src);

Compliant result: an empty array, or only scripts whose blocking is intentional (an A/B testing anti-flicker script, for example).

Other methods:

  • PageSpeed Insights or Lighthouse: the audit on render-blocking resources should no longer list any script, and Total Blocking Time should drop. See analyze PageSpeed Insights and Lighthouse (opens in a new tab).
  • Developer tools, Coverage tab (Ctrl+Shift+P, then “Coverage”): reload the page. A script whose code remains almost entirely unused at load time is a good candidate.
  • Performance tab: record a page load and spot the long tasks attributed to secondary scripts before the LCP.

How to implement

Before you start

Sort each script into one of these three families, then apply the matching technique:

Family Examples Technique
Needed for the initial render anti-flicker script, small inline theme script leave as is, keep it tiny
Needed for page interactivity menu, cart, forms, framework defer or type="module"
Secondary chat, reviews, video, map, social sharing load on idle, on visibility or on click

Basic tag for the second family:

<script src="/js/app.js" defer></script>

Loading when the browser is idle, for the third family:

<script>
  function loadScript(src) {
    var script = document.createElement('script');
    script.src = src;
    script.async = true;
    document.head.appendChild(script);
  }

  window.addEventListener('load', function () {
    var whenIdle = window.requestIdleCallback || function (callback) {
      return setTimeout(callback, 2000);
    };

    whenIdle(function () {
      loadScript('https://widget.example.com/chat.js');
    });
  });
</script>

Loading when the block approaches the viewport:

<div id="reviews"></div>
<script>
  var target = document.getElementById('reviews');
  var observer = new IntersectionObserver(function (entries) {
    if (!entries[0].isIntersecting) {
      return;
    }

    observer.disconnect();
    var script = document.createElement('script');
    script.src = '/js/reviews.js';
    document.head.appendChild(script);
  }, { rootMargin: '300px' });

  observer.observe(target);
</script>

In a bundle, the equivalent is a dynamic import: import('./reviews.js') only downloads the module when it is called.

Warning: an inline script that uses a deferred library (jQuery(...) while jQuery is loaded with defer) runs before it and throws an error. Move this code into a deferred file loaded after the library, or wrap it in a DOMContentLoaded listener.

WordPress

Versions WordPress 6.3 to 7.1; LiteSpeed Cache 7.x; WP Rocket, Autoptimize and Perfmatters in their November 2026 versions.

Since WordPress 6.3, the loading strategy is declared when the script is registered, in the theme's functions.php or in a plugin:

add_action('wp_enqueue_scripts', function (): void {
    wp_enqueue_script(
        'theme-app',
        get_theme_file_uri('assets/js/app.js'),
        [],
        '1.4.0',
        [
            'strategy' => 'defer',
            'in_footer' => true,
        ]
    );
});

For a script registered by a third-party plugin, add the strategy afterwards:

add_action('wp_enqueue_scripts', function (): void {
    wp_script_add_data('handle-de-l-extension', 'strategy', 'defer');
}, 100);

WordPress checks the dependency tree: if a blocking script depends on a script declared with defer, the latter falls back to classic loading so that nothing breaks. Check the HTML output.

With an optimization plugin:

  • WP Rocket: File Optimization tab, JavaScript Files section, the options to load JavaScript deferred and to delay JavaScript execution until the first interaction.
  • LiteSpeed Cache: Page Optimization > JS Settings > Load JS Deferred (Deferred or Delayed).
  • Autoptimize: Settings > Autoptimize > JS, CSS & HTML, option “Do not aggregate but defer?”.
  • Perfmatters: Assets > JavaScript, Defer and Delay options.

After each activation, purge the cache and test the menu, forms, cart and search. Delaying until the first interaction is powerful but risky: exclude from it any script that produces visible content or structured data, since Googlebot does not interact.

Shopify

Versions Online Store 2.0 themes (Dawn and derivatives), Shopify admin, November 2026.

In layout/theme.liquid and in sections, load the theme files with defer:

<script src="{{ 'theme.js' | asset_url }}" defer="defer"></script>

The script_tag filter produces a tag with no attribute, and therefore a blocking one: replace {{ 'theme.js' | asset_url | script_tag }} with the tag above. The Dawn theme and its derivatives already follow this pattern.

Scripts injected by apps largely escape the theme's control. Disable unnecessary embeds in Online Store > Themes > Customize > App embeds and see limit third-party scripts (opens in a new tab).

PrestaShop

Versions PrestaShop 8 and 9.

Theme and module scripts are placed at the bottom of the page by default (position: bottom). To add defer or async from a module or a controller:

public function setMedia()
{
    parent::setMedia();

    $this->registerJavascript(
        'module-monmodule-widget',
        'modules/' . $this->module->name . '/views/js/widget.js',
        [
            'position' => 'bottom',
            'priority' => 200,
            'attributes' => 'defer',
        ]
    );
}

In a theme's config/theme.yml, the key is singular:

assets:
  js:
    all:
      - id: theme-extras
        path: assets/js/extras.js
        priority: 200
        attribute: defer

Then clear the cache in Advanced Parameters > Performance.

Magento

Versions Adobe Commerce and Magento Open Source 2.4.x (up to 2.4.9). Luma theme or a derivative.

Adobe Commerce and Magento Open Source load most of their JavaScript through RequireJS, asynchronously. Two complementary levers:

bin/magento config:set dev/js/move_script_to_bottom 1
bin/magento cache:flush

This setting moves scripts to the end of the page. For a script added by a theme or a module, declare the attribute in the layout (view/frontend/layout/default_head_blocks.xml):

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <script src="Vendor_Module::js/widget.js" defer="true"/>
    </head>
</page>

The Hyvä theme replaces RequireJS with Alpine.js and loads much less JavaScript: the question then mostly concerns third-party scripts.

Drupal

Versions Drupal 10 and 11.

Drupal places library scripts at the bottom of the page, unless header: true is specified. Add defer in the montheme.libraries.yml file:

global-scripts:
  js:
    js/app.js: { attributes: { defer: true } }
  dependencies:
    - core/drupal

Clear the cache (drush cr). Also enable aggregation in Configuration > Development > Performance.

Joomla

Versions Joomla 4 to 6.

Since Joomla 4, use the Web Asset Manager, in the template's index.php or in an extension:

$wa = $this->getWebAssetManager();
$wa->registerAndUseScript(
    'template.app',
    'templates/montemplate/js/app.js',
    [],
    ['defer' => true]
);

Wix

Versions Wix dashboard, premium plans with a connected domain, November 2026.

The loading of the platform's own scripts cannot be configured. For your own snippets (Settings > Custom Code), choose the “Body - end” placement rather than “Head”.

Squarespace

Versions Squarespace 7.1, Core plans and above, November 2026.

Same logic: place custom code in the Footer field of Code Injection, and add defer or async to your <script src> tags.

Webflow

Versions Webflow, paid site plans, November 2026.

In Site settings > Custom code, use the “Footer code” field and add defer to every external tag. Webflow's own scripts are already placed at the end of the page.

Laravel

Versions Laravel 10 to 13, with Vite.

With Vite, the Blade directive produces modules, which are deferred by nature:

<head>
    @vite(['resources/css/app.css', 'resources/js/app.js'])
</head>

For a script outside the bundle, write the attribute yourself and keep page-specific scripts in a stack placed before </body>:

<script src="{{ asset('js/widget.js') }}" defer></script>
@stack('scripts')

Split the bundle with dynamic imports (import('./map.js')) for code that is only used on some pages.

Symfony

Versions Symfony 6.4, 7.4 and 8.x (AssetMapper or Webpack Encore).

With AssetMapper, {{ importmap('app') }} generates ES modules, which are deferred by nature. With Webpack Encore, check that the attribute is enabled in config/packages/webpack_encore.yaml:

webpack_encore:
    output_path: '%kernel.project_dir%/public/build'
    script_attributes:
        defer: true

{{ encore_entry_script_tags('app') }} then produces tags with defer.

Next.js

Versions Next.js 15 and 16 (App Router).

The framework already defers its own bundles. For external scripts, use next/script and choose the strategy:

import Script from 'next/script';

export default function Layout({ children }) {
  return (
    <>
      {children}
      <Script src="https://widget.example.com/chat.js" strategy="lazyOnload" />
    </>
  );
}

afterInteractive (the default value) loads the script after hydration, lazyOnload during idle time. Keep beforeInteractive for the rare scripts that are essential before hydration.

For a heavy, secondary component, load it on demand:

'use client';

import dynamic from 'next/dynamic';
import { useState } from 'react';

const Chat = dynamic(() => import('./Chat'), { ssr: false });

export default function ChatButton() {
  const [open, setOpen] = useState(false);

  return (
    <>
      <button type="button" onClick={() => setOpen(true)}>Open chat</button>
      {open && <Chat />}
    </>
  );
}

Nuxt

Versions Nuxt 3.16 and later and Nuxt 4; Nuxt Scripts module 1.x.

Nuxt defers its bundles. For an external script:

useHead({
  script: [
    { src: 'https://widget.example.com/chat.js', defer: true },
  ],
});

The Nuxt Scripts module goes further with triggers (idle time, interaction, element visibility):

useScript('https://widget.example.com/chat.js', {
  trigger: useScriptTriggerInteraction({ events: ['scroll', 'click', 'keydown'] }),
});

Prefix a component with Lazy (<LazyChatWidget v-if="open" />) so that its code is only downloaded when it is displayed.

Astro

Versions Astro 5 to 7.

A <script> tag with no attribute in a component is processed by Astro: bundled, then served as type="module". An is:inline tag is copied as is: add defer to it.

For framework components (React, Vue, Svelte), the directive controls when hydration happens:

<Search client:idle />
<Reviews client:visible />

Without a client:* directive, the component is rendered as HTML with no JavaScript.

Cloudflare

Versions Cloudflare dashboard, Rocket Loader, all plans, November 2026.

Rocket Loader (Speed > Settings > Content Optimization) defers all the scripts on the page until after rendering, without changing the code. It is available on all plans. To exclude a script from it:

<script data-cfasync="false" src="/js/critical.js"></script>

Warning: Rocket Loader rewrites <script> tags and can break inline scripts, plugins or a strict CSP. Test it in a staging environment, and prefer a fix at the source when you control the code.

Common mistakes

  • Putting async on dependent scripts: the execution order is no longer guaranteed, and a jQuery plugin can run before jQuery. Use defer.
  • Adding defer to an inline script: the attribute is ignored.
  • Delaying everything until the first interaction: the content, structured data or analytics that depend on these scripts no longer exist for crawlers or for visitors who do not touch the page.
  • Deferring the script that builds the main content: on a client-side rendered site, this delays the LCP instead of improving it. See prefer SSR or SSG for critical content if relevant (opens in a new tab).
  • Deferring an A/B testing anti-flicker script: the original page is displayed, then changes before the visitor's eyes.
  • Combining two mechanisms: Rocket Loader plus the delay option of a caching plugin produce unpredictable execution orders. Pick one.
  • Not retesting user journeys: a deferred script that fails does not break the display, but it does break the form or the cart. Test conversions after every change.

Frequently asked questions

What is the difference between defer and async?

Both attributes download the script in parallel without blocking HTML parsing. With defer, scripts run after HTML parsing, in document order, before DOMContentLoaded: this is the right choice for the site's own scripts and for scripts that depend on one another. With async, each script runs as soon as it arrives, with no guaranteed order: keep it for independent scripts.

Does deferring scripts improve INP?

Partly. Deferring removes the blocking of the first display, but a heavy script executed right after HTML parsing still occupies the main thread and delays the response to the first clicks. Truly secondary scripts, such as a chat, reviews or a map, benefit from being loaded even later: when the browser is idle, when their block approaches the viewport, or when the visitor clicks.

Is delaying JavaScript until the first interaction risky for SEO?

Yes, for any script that produces content. Googlebot executes JavaScript but does not click or scroll the page: content, structured data or analytics that wait for an interaction do not exist for it. Keep this delay for scripts with no content to index, exclude the others in your plugin's settings, then test the menu, forms and cart.

Should I enable Cloudflare Rocket Loader?

Only if you do not control the code. Rocket Loader defers all the scripts on the page without changing the theme, and it is available on all plans, but it rewrites script tags and can break inline scripts, plugins or a strict CSP. Test it in a staging environment and do not combine it with the delay option of a caching plugin.

Updated on

Topic checklist (PDF)

And now?

In the “Performance and Core Web Vitals” topic

  1. Analyze PageSpeed Insights and Lighthouse
  2. Analyze real-user CrUX data
  3. Target LCP ≤ 2.5 s at the 75th percentile
  4. Target INP ≤ 200 ms at the 75th percentile
  5. Target CLS ≤ 0.1 at the 75th percentile
  6. Target TTFB ≤ 800 ms as a benchmark
  7. Optimize hosting and CDN
  8. Enable Brotli/Gzip
  9. Configure browser and server caching
  10. Minify CSS and JavaScript
  11. Remove unused CSS/JS
  12. Reduce render-blocking resources
  13. Defer non-essential scripts
  14. Limit third-party scripts
  15. Optimize database queries
  16. Optimize fonts (WOFF2, font-display)
  17. Preload only critical resources
  18. Optimize the LCP image without lazy loading
  19. Lazy-load offscreen content
  20. Reserve space for media and ads
  21. Reduce DOM complexity
  22. Test before and after cookie consent
  23. Test on a slow mobile connection
  24. Set a performance budget
  25. Preload likely navigations with Speculation Rules
  26. Make pages eligible for the back/forward cache (bfcache)
  27. Diagnose INP with Long Animation Frames (LoAF)