Skip to main content
KadiCache
Browse 37 Docs Guides & Search

Defer Non-Critical JavaScript & jQuery Dependency Safety

Eliminate render-blocking <script> tags in DOM order while protecting inline jQuery calls, document.write() parser scripts, Slider Revolution, and A/B testing SDKs.

Optimization/ScriptOptimizer.phpOptimization/ParserDependentScripts.phpIntegrations/Themes/ThemeCompatibility.php
WP Admin -> KadiCache -> CSS & JavaScript (Defer & Delay JS)
MODULE 15 · 2X RETINA
JavaScript Minification, Defer, and Delay execution controls with automatic jQuery and WooCommerce safeguards.2880×1840 WebP
Quick Summary · 30-Second Operational SpecSource-Verified Guide
WP Admin Path
WP Admin -> KadiCache -> CSS & JavaScript (Defer JS)
Expected Outcome
Zero Parser-Blocking <script> Tags · Safe jQuery Chains
Key Marker / Engine
ScriptOptimizer.php | ParserDependentScripts.php | defer
  • Adds standard HTML5 defer to eligible classic <script src="..."> tags (ScriptOptimizer.php) so scripts download in parallel without pausing HTML parsing, then execute in exact DOM order.
  • Prevents Uncaught ReferenceError: jQuery is not defined by analyzing inline <script> blocks, WordPress dependency handles (synchronousDependencies()), ThemeCompatibility, and Slider Revolution (RS_REVISION >= 6.5.5).
  • Scans scripts via ParserDependentScripts.php to keep legacy document.write() tags synchronous automatically.
  • Ships built-in DEFAULT_EXCLUSIONS protecting Stripe, PayPal, reCAPTCHA, Cloudflare Turnstile, hCaptcha, Cookiebot, OneTrust, Optimizely, VWO, and AB Tasty.

How Synchronous <head> Scripts Stall HTML Parsing (And How defer Fixes It)#

Whenever a browser’s HTML parser encounters a classic <script src="/wp-includes/js/jquery/jquery.min.js"></script> tag without defer or async, HTML parsing halts immediately. The browser cannot discover images further down the document, build the layout tree, or paint above-the-fold text until that script finishes downloading and executing on the main thread.

Adding the native HTML5 defer attribute changes the browser timeline cleanly:

  1. Non-Blocking Parallel Download: The browser fetches deferred .js files in the background at lower network priority while continuing to parse HTML and render your LCP hero banner uninterrupted.
  2. Guaranteed Sequential Order Before DOMContentLoaded: Unlike async (which executes scripts in random arrival order and breaks dependent plugins!), defer guarantees that Script 1 (jquery.min.js), Script 2 (woocommerce.min.js), and Script 3 (theme.js) execute in exact document order right after HTML parsing finishes.

Why Naive defer Plugins Cause jQuery is not defined on WordPress#

If HTML5 defer preserves order across external <script src="..."> files, why do simple code-snippet plugins that slap defer onto every script tag crash half of WordPress plugins? Because the HTML5 specification applies defer ONLY to external scripts with a src attribute—inline <script>jQuery(function($){ ... });</script> blocks ignore defer and execute immediately during HTML parsing!

If jquery-core is deferred until the end of </html>, while an inline WooCommerce widget or Slider Revolution initialization block in <body> runs immediately at line 420, the inline block crashes with Uncaught ReferenceError: jQuery is not defined.

KadiCache Free Core (ScriptOptimizer.php + ParserDependentScripts.php) inspects the entire HTML document before deferring a single script so dependency chains never break:

Dependency Scenario Detected in HTMLHow ScriptOptimizer.php Handles It SafelyResult in Browser Console
Inline jQuery(...) / $(...) script in <body>Coordinates jQuery scope & dependent handles (synchronousDependencies()) so inline calls never fire before jquery-core0 ReferenceErrors
Slider Revolution (RS_REVISION >= 6.5.5) async heroDetects hasAsyncHeroSlider($html) and keeps jquery ready when hero initialization requires itInstant hero slider boot
Script calling document.write() (ParserDependentScripts.php)Scans local script sources & inline calls; keeps parser-dependent scripts synchronous through $nativeThroughLegacy embeds render intact
A/B Testing Anti-Flicker SDKs (Optimizely, VWO, AB Tasty)Built into ScriptOptimizer::DEFAULT_EXCLUSIONS (cdn.optimizely.com, visualwebsiteoptimizer.com, abtasty.com)Zero experiment flicker
Payment, Captcha & Consent SDKsProtects js.stripe.com, paypal.com/sdk/js, recaptcha, turnstile, hcaptcha, cookiebot, cookielaw.orgImmediate checkout & GDPR banners
FIG 01Selecting Defer Non-Critical JavaScript and reviewing jQuery/dependency compatibility inside WP Admin -> KadiCache -> CSS & JavaScriptZoom 2x

When to Choose Defer JS Alone vs Defer + Delay Until Interaction#

Inside WP Admin -> KadiCache -> CSS & JavaScript, KadiCache supports both strategies cleanly (ScriptOptimizer.php even cascades automatically alongside DelayJsOptimizer.php for scripts not held by interaction delay!):

  • Use Defer Non-Critical JavaScript on Its Own When: Your site runs complex interactive dashboards, real-time financial charts, LMS quizzes, or live calculators that must initialize automatically on page load without waiting for user scroll/tap—eliminating <head> render-blocking warnings while running every script automatically right after HTML parse.
  • Use Delay Until Interaction (Cascaded With Defer) When: Your site is a WooCommerce storefront, marketing landing page, publisher blog, or agency site loading Google Tag Manager, Meta Pixel, chat widgets, and heavy UI bundles—holding non-essential third-party CPU work until interaction while ScriptOptimizer cleanly defers remaining active scripts (Delay JS Guide).

Configuring Defer JS Exclusions & Developer Attributes#

Need a specific third-party anti-flicker or header script to remain synchronous in <head>?

  1. Defer JavaScript Exclusions (defer_js_exclusions): Expand the Excluded Defer JS drawer in WP Admin -> KadiCache -> CSS & JavaScript and add the script filename (ab-test-head.js), handle ID, or domain.
  2. Excluded Defer Page Paths (defer_js_excluded_paths): Bypass Defer JS on specific routes (/legacy-calculator/*), or check Disable: Defer JavaScript in the Gutenberg sidebar (Per-Page Exclusions).
  3. HTML Attribute Opt-Out (data-kadicache-no-defer or data-no-defer): Add data-kadicache-no-defer directly onto any <script> tag in PHP templates:
HTMLKeeping a Custom Head Script Synchronous via Attribute
<script src="/wp-content/themes/custom/js/critical-theme-mode.js"
        data-kadicache-no-defer></script>

Best Practices for Theme Developers Writing Defer-Friendly WordPress Code#

If you author custom agency themes or WooCommerce extensions, following three native WordPress standards ensures 100% zero-configuration compatibility with Defer Non-Critical JavaScript:

  1. Declare Explicit Script Handle Dependencies: Always pass ['jquery'] (or ['wp-element'] / ['wc-cart-fragments']) in the $deps parameter of wp_enqueue_script() rather than printing raw <script> tags inside wp_head.
  2. Attach Inline Initialization via wp_add_inline_script(): WordPress associates wp_add_inline_script('my-theme', '...', 'after') directly with the parent handle so ScriptOptimizer.php sees the exact relationship.
  3. Use DOMContentLoaded in Standalone Vanilla JS Snippets: Wrapping standalone inline scripts in document.addEventListener('DOMContentLoaded', function () { ... }) ensures deferred libraries have finished executing before your handler runs.

Frequently Asked Operational Questions

Why does KadiCache use defer instead of async on WordPress scripts?
async executes scripts the instant each network download finishes—meaning a small 4 KB jQuery plugin can finish downloading and execute BEFORE the 32 KB jquery.min.js library finishes, crashing randomly! defer downloads in parallel just like async, but strictly preserves 1 -> 2 -> 3 execution order.
Does Defer JavaScript run on WooCommerce Cart and Checkout pages?
No. ScriptOptimizer.php explicitly bypasses is_cart(), is_checkout(), and is_account_page() (as well as Stripe, PayPal, Turnstile, and reCAPTCHA SDKs everywhere) so payment forms never face script timing changes.
Will Defer JavaScript cause flicker if I run Optimizely, VWO, or AB Tasty A/B tests?
No. ScriptOptimizer::DEFAULT_EXCLUSIONS automatically excludes cdn.optimizely.com, visualwebsiteoptimizer.com, and try.abtasty.com so synchronous anti-flicker experiment snippets run in <head> as designed.
Does Defer JavaScript work alongside Cloud Remove Unused CSS?
Yes—combining Inline Used CSS (zero render-blocking stylesheets) with Defer/Delay JavaScript (zero render-blocking scripts) removes every render-blocking asset from <head> simultaneously.
What if a script uses ES Modules (<script type="module">)?
Browser specifications already treat <script type="module"> as deferred by default! ScriptOptimizer leaves module tags clean without adding redundant attributes.
Gergis — Lead Systems & Cache Architect
Principal WordPress & Cloud Edge Architect
E-E-A-T Source Verified

Creator of KadiCache’s Early PHP Drop-In, 7-Driver Object Cache Engine, Cloud Remove Unused CSS, and Zero-CLS Lazy Render pipeline.

apps/wordpress-plugin/src/Optimization/ScriptOptimizer.phpapps/wordpress-plugin/src/Optimization/ParserDependentScripts.phpapps/wordpress-plugin/src/Integrations/Themes/ThemeCompatibility.php
Was this engineering guide helpful?