If you try to defer javascript wordpress without breaking your site, you usually end up with Uncaught ReferenceError: jQuery is not defined within minutes. Deferring scripts shifts asset execution until after the HTML document parses, which immediately breaks plugins that dump raw, inline <script> tags directly into template files. You can eliminate render-blocking assets and improve Total Blocking Time (TBT) without breaking functional dependencies.
Quick answer
- Use WordPress 6.3+ core strategies: Pass
['strategy' => 'defer']directly insidewp_enqueue_script()orwp_register_script()instead of string manipulation filters. - Protect inline scripts: Wrap orphaned inline JavaScript in a
DOMContentLoadedevent listener or execute viawp_add_inline_script()tied to an enqueued handle. - Keep jQuery render-blocking if necessary: If legacy plugins require inline execution in the document body, defer your custom theme code and analytics, but leave jQuery untouched.
- Use
wp_script_add_data()for plugins: Apply loading strategies retroactively to third-party assets without deregistering them. - Delay heavy third-party tags: Shift non-critical marketing trackers (Tag Manager, pixel trackers) to execute on user interaction rather than simple deferral.
Why deferring JavaScript breaks WordPress sites
To fix the breakages, you need to understand the browser execution timeline. When an external script is marked with defer, the browser downloads the file in parallel with HTML parsing, but delays execution until the HTML parsing finishes, just before DOMContentLoaded fires. Deferred scripts also maintain their relative execution order based on their location in the markup.
Problems occur because of inline scripts. In standard WordPress architecture, many themes and older plugins output inline scripts directly into the HTML stream like this:
<script>
jQuery(document).ready(function($) {
$('.slider').slick();
});
</script>
Browsers parse and execute unflagged inline scripts immediately upon discovery. If jQuery was marked with defer, the browser pauses HTML parsing to execute that inline block before the deferred jquery.js file has executed. The variable jQuery does not exist in global memory yet, throwing a fatal ReferenceError and stopping execution of the rest of the inline block.
Defer preserves execution order between deferred external files, but unflagged inline scripts execute instantly. If an inline script relies on a deferred file, it will fail every time.
How to defer javascript wordpress without breaking dependencies
WordPress 6.3 introduced formal script loading strategies through the wp_enqueue_script() API. You no longer need to write fragile script_loader_tag regex replacements that break script attributes or duplicate tags.
1. Register scripts with native strategies
When registering theme or plugin scripts, pass an array for the $args parameter instead of a boolean $in_footer value. Specify 'strategy' => 'defer':
add_action('wp_enqueue_scripts', function () {
wp_register_script(
'theme-navigation',
get_theme_file_uri('/assets/js/nav.js'),
['jquery'],
'1.0.0',
[
'in_footer' => true,
'strategy' => 'defer',
]
);
wp_enqueue_script('theme-navigation');
});
If a script declared with 'strategy' => 'defer' depends on another script that is also deferred, WordPress outputs both with the defer attribute, preserving their dependency order in the HTML document.
2. Apply strategies to third-party scripts via hooks
For scripts enqueued by active plugins that you cannot edit directly, use wp_script_add_data(). Hook into wp_enqueue_scripts with a late priority (such as 100) so the original handles are already registered:
add_action('wp_enqueue_scripts', function () {
// Defer a plugin script safely without deregistering
wp_script_add_data('contact-form-7', 'strategy', 'defer');
wp_script_add_data('woocommerce-general', 'strategy', 'defer');
}, 100);
WordPress handles the dependency tree automatically. If you attempt to defer an asset whose dependency is marked as blocking, WordPress intelligently maintains standard execution to avoid breaking dependent logic.
Handling jQuery dependencies and inline scripts safely
If you defer jquery-core, any plugin printing an unmanaged inline script will break. You have three practical ways to address this.
Option A: The recommended modern approach (Keep jQuery blocking, defer everything else)
In standard client builds containing WooCommerce or diverse plugins, the highest return on investment with zero breakage comes from leaving jquery-core render-blocking in the <head> or footer, while deferring all theme assets, UI libraries, and analytics.
add_action('wp_enqueue_scripts', function () {
// Target your own bundles and heavy libraries
$deferred_handles = [
'alpinejs',
'swiper-slider',
'theme-main-bundle',
];
foreach ($deferred_handles as $handle) {
wp_script_add_data($handle, 'strategy', 'defer');
}
}, 100);
This isolates and shrinks render-blocking execution to just jQuery Core (roughly 30KB compressed), satisfying PageSpeed tests without generating console errors.
Option B: Rewrite inline scripts using wp_add_inline_script
If you control the codebase and want jQuery deferred, eliminate raw <script> tags. Move all inline logic into wp_add_inline_script(). WordPress then binds the inline code to the deferred script's lifecycle:
add_action('wp_enqueue_scripts', function () {
wp_enqueue_script(
'custom-gallery',
get_theme_file_uri('/js/gallery.js'),
['jquery'],
'1.0.0',
['strategy' => 'defer', 'in_footer' => true]
);
// This will print inline attributes that preserve execution timing
$inline_code = 'jQuery(function($){ $(".gallery").customInit(); });';
wp_add_inline_script('custom-gallery', $inline_code, 'after');
});
Option C: The Event Buffer fallback for legacy plugins
If you must defer jQuery on a site with legacy plugins dumping inline jQuery, install a small, synchronous buffer script in the <head> that intercepts calls to jQuery() or $(document).ready() and holds them in an array until jQuery actually initializes:
<script>
// Place this directly in header.php before any other scripts
window.deferredJQueryQueue = [];
window.$ = window.jQuery = function(callback) {
if (typeof callback === 'function') {
window.deferredJQueryQueue.push(callback);
}
return window.jQuery;
};
</script>
Then, attach an execution runner using wp_add_inline_script() tied to the deferred jquery-core handle:
add_action('wp_enqueue_scripts', function () {
if (is_admin()) {
return;
}
wp_script_add_data('jquery-core', 'strategy', 'defer');
$runner = '
if (window.deferredJQueryQueue && window.deferredJQueryQueue.length) {
window.deferredJQueryQueue.forEach(function(fn) { fn(jQuery); });
window.deferredJQueryQueue = [];
}
';
wp_add_inline_script('jquery-core', $runner, 'after');
}, 100);
Use this buffer approach with caution. It catches standard ready functions ($(function() { ... })), but it will not intercept direct object accesses like $.ajax() or property reads like $.browser.
Defer vs. Delay: When defer is not enough
Deferring downloads a file immediately and executes it at document parsing completion. For heavy, non-essential third-party JavaScript—like Google Tag Manager, Meta Pixel, Hotjar, or live chat widgets—deferring still hurts your Interaction to Next Paint (INP) and Total Blocking Time (TBT) metrics.
These scripts do not need to execute on document completion. They need to be delayed until actual user interaction occurs.
// delay-scripts.js: Load analytics only when the user scrolls, moves, or taps
(function() {
const userEvents = ['keydown', 'mousemove', 'wheel', 'touchmove', 'touchstart'];
function triggerScripts() {
userEvents.forEach(event => window.removeEventListener(event, triggerScripts, { passive: true }));
const script = document.createElement('script');
script.src = 'https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX';
script.async = true;
document.head.appendChild(script);
}
userEvents.forEach(event => {
window.addEventListener(event, triggerScripts, { once: true, passive: true });
});
})();
Reserve deferral for theme functionality that renders your visual layout (mobile menus, sliders, tabs). Use interaction delays for conversion trackers and tracking pixels.
Troubleshooting common defer errors
When a deferred script configuration fails, check these three common points of failure:
- Uncaught TypeError: $(...) is not a function: An inline script loaded before jQuery finished executing its deferred task. Move the inline script into a
.jsfile enqueued via standard dependencies, or remove the defer attribute fromjquery-core. - Broken admin bar or Customizer: Never apply global defer filters indiscriminately to
script_loader_tagwithout excluding administrative contexts. Always wrap modifications with conditional checks:if (is_admin() || is_customize_preview()) return;. - WooCommerce checkout validation failures: Scripts like
wc-checkoutand Stripe payment gateway bridges rely on precise event timing during form submission. Deferring gateway scripts often creates silent submission loops. Excludeis_checkout()andis_cart()from aggressive defer pipelines.
Checklist
- Ensure the site is running WordPress 6.3 or higher to use the official script loading strategies API.
- Audit active theme and plugin handles using the Query Monitor plugin to isolate what is render-blocking.
- Exclude
is_admin(),is_cart(), andis_checkout()from custom deferral functions. - Verify whether
jquery-corecan safely be deferred or if inline plugin scripts necessitate keeping it blocking. - Apply
'strategy' => 'defer'usingwp_register_script()orwp_script_add_data()on handles, avoiding regex onscript_loader_tag. - Refactor custom inline script tags into
wp_add_inline_script()mapped to proper parent script dependencies. - Move tracking pixels, chat widgets, and Tag Manager containers from deferral to user-interaction delays.
- Test your implementation in an Incognito browser session while monitoring the DevTools Console for
ReferenceErrorwarnings.
- Web Vitals (web.dev)Web Vitals (web.dev)
- Lighthouse overviewLighthouse overview
Drafted with AI assistance. Code targets current WordPress, WooCommerce and Next.js APIs; test changes on a staging site before production.