Skip to main content
KadiCache
Core & Object CacheFree Core

Defer & Safe Delay JavaScript

Defers non-critical scripts and safely delays heavy third-party/theme JavaScript until first user interaction while protecting parser-dependent scripts, CSP policies, WooCommerce carts, and 6 major wishlist counters.

Main-Thread TBT Target
0 ms
Verified Source Entry
apps/wordpress-plugin/src/Optimization/DelayJsOptimizer.php
Verified Engine Capabilities

Engineered for zero regressions.

  • Smart DelayScriptClassifier separates safe third-party scripts from parser-dependent inline blocks
  • Respects Content Security Policy headers and native <body onload> semantics
  • Developer opt-out via data-kadicache-no-delay on any script or interactive subtree
  • Refreshes WooCommerce mini-cart and 6 wishlist counters before releasing delayed jQuery
Opting Out a Specific Script or Interactive Subtree in Markup
<!-- 1. Keep an individual script immediate while delaying the rest of the page -->
<script src="/wp-content/themes/storefront-child/js/live-price-calculator.js"
        data-kadicache-no-delay></script>

<!-- 2. Protect an entire interactive header or calculator container -->
<section class="financing-widget" data-kadicache-no-delay>
  <script>window.initFinancingWidget();</script>
</section>
Inside the KadiCache WordPress Plugin

Defer & Safe Delay JavaScript — Plugin Interface

2 live 2x Retina plugin screens
WP Admin -> KadiCache -> CSS & JavaScript (Defer & Delay JS)
MODULE 04 · 2X RETINA
JavaScript Minification, Defer, and Delay execution controls with automatic jQuery and WooCommerce safeguards.2880×1840 WebP
100% Source-Code Verified9 min engineering readUpdated 2026-11-23
Executive Summary · 30-Second SpecZero-Regressions Spec
WP Admin Path
WP Admin -> KadiCache -> CSS & JavaScript
Measured Impact
0 ms Initial TBT · Sub-100 ms p75 INP
Verification Marker
data-kadicache-defer | data-kadicache-no-delay
  • Separates non-blocking Defer JavaScript from Delay Until Interaction so site owners can choose conservative compatibility or maximum main-thread relief.
  • Automatically protects parser-dependent inline scripts, Content-Security-Policy nonces/hashes (CspPolicy.php), GDPR consent banners (ConsentScripts.php), payment SDKs, and multilingual switchers.
  • Guards WooCommerce single-product galleries (wc-single-product, zoom, flexslider, photoswipe), mini-cart fragments, and 6 popular wishlist counter plugins.
  • Provides independent Delay, Defer, and Minify exclusion drawers plus Keep delaying scripts for shoppers for stores with active carts.
Table of Contents (5 sections)

Why Third-Party & Theme JavaScript Dominates Mobile Main-Thread Blocking#

Even after Early PHP Drop-In Page Caching cuts server Time to First Byte (TTFB) below 20 milliseconds, modern WordPress and WooCommerce pages routinely stall on mid-range mobile phones for 1.5 to 4.0 seconds. The culprit is synchronous and early main-thread JavaScript evaluation. A typical commercial storefront loads jQuery core, theme navigation bundles, Elementor frontend handlers, Swiper carousels, Google Tag Manager, Meta Pixel, TikTok analytics, live chat widgets, review badges, and customer heatmaps—often totaling 650 KB to 1.8 MB of compressed JavaScript (2.5 MB+ uncompressed) during initial page load.

On mobile CPUs, downloading scripts is only the beginning. Every <script> without defer or async pauses the HTML parser, forces V8 or JavaScriptCore to parse and compile bytecode on the main UI thread, and triggers long tasks (> 50 ms) that inflate Lighthouse Total Blocking Time (TBT) and degrade real-visitor Interaction to Next Paint (INP). If a visitor taps a mobile menu icon or product size swatch while a 280 ms third-party analytics bundle is executing, the browser cannot paint the visual response until that task finishes.

Naive "delay all JavaScript" plugins attempt to fix TBT by blindly rewriting every <script> tag on the page to a fake MIME type until the user moves a mouse or touches the screen. In production WordPress environments, blind script delaying causes four immediate regressions:

  1. Blank Hero Sections & Frozen Preloaders: Themes with CSS entrance animations (elementor-invisible, data-aos, data-sal) or full-screen page-loader overlays stay invisible until the visitor taps an apparently blank white screen.
  2. Broken WooCommerce Product Galleries & Express Checkout: Single-product image zoom, FlexSlider thumbnails, PhotoSwipe lightboxes, Stripe Payment Elements, PayPal buttons, and Cloudflare Turnstile challenges fail to render above the fold.
  3. Compliance & Consent Violations: Delaying Cookiebot, OneTrust, Complianz, or CookieYes prevents mandatory GDPR/ePrivacy consent banners from appearing on initial arrival.
  4. Strict Content-Security-Policy (CSP) Failures: Injecting inline bootstrapper scripts onto sites running hash-based or nonce-less script-src headers triggers browser CSP violations that block script execution completely.

KadiCache eliminates those trade-offs in Free Core through ScriptOptimizer.php, DelayJsOptimizer.php, and DelayScriptClassifier.php—combining clean HTML5 defer orchestration with a context-aware Delay Until Interaction engine.

Choosing the Right Execution Mode: Off vs Defer vs Delay Until Interaction#

Inside WP Admin -> KadiCache -> CSS & JavaScript (and Step 2 of the guided Setup Wizard), KadiCache presents clear execution modes rather than forcing every site into aggressive script rewriting:

JavaScript StrategyHow Scripts Load & RunIdeal WordPress Use CaseTypical Mobile TBT & INP Impact
Off (Original Order)Leaves script tags untouched (Minify JS can still compress local assets)Legacy custom web apps relying on synchronous document.write()Baseline (400 – 1,400 ms TBT)
Defer Non-Critical JSAdds defer while preserving exact DOM execution order across dependent chainsContent portals, membership sites, and complex interactive calculatorsCuts parser blocking (90 – 240 ms TBT)
Delay Until InteractionHolds non-essential theme & third-party scripts in inert type="text/plain" state until first user action (or optional fallback timer)WooCommerce stores, marketing landing pages, Elementor/Divi sites, ad-heavy blogsNear-zero initial TBT (0 – 40 ms · < 100 ms INP)

When Defer Non-Critical JavaScript is active, ScriptOptimizer.php inspects the full dependency chain before adding defer. Any script that calls document.write() (ParserDependentScripts.php) or inline initialization block that depends on an un-deferred synchronous parent is kept in safe order so jQuery is not defined errors do not occur.

When Delay Until Interaction is active (DelayJsOptimizer.php, guarded by a MAX_HTML = 2,097,152 byte document safety ceiling), KadiCache classifies every script on the page before deciding whether to keep it live on initial paint or hold it until the visitor scrolls, taps, clicks, presses a key, or moves the pointer.

Built-In Safeguards Inside DelayJsOptimizer.php & DelayScriptClassifier.php#

Rather than forcing site owners to hunt down dozens of obscure script handles manually, KadiCache ships deterministic compatibility classifiers verified across popular WordPress ecosystems:

  • WooCommerce Gallery & Shopper Continuity: On single WooCommerce product templates, KadiCache automatically protects GALLERY_HANDLES (wc-single-product, zoom, flexslider, photoswipe, photoswipe-ui-default) so product photography, variation gallery swaps, and zoom lenses respond on first tap. Meanwhile, mini-cart counters and 6 supported wishlist plugins refresh cleanly without prematurely waking heavy marketing tags. By default, when a shopper has items in their cart, KadiCache relaxes script delaying for maximum checkout responsiveness—or you can toggle Keep delaying scripts for shoppers (keep_delaying_for_shoppers) when third-party chat/analytics tags still weigh down active shopping sessions.
  • Payment Gateways, Bot Challenges & Consent Managers: INDEPENDENT_SDKS and ConsentScripts.php automatically recognize Stripe, PayPal, Cloudflare Turnstile, Google reCAPTCHA, hCaptcha, Cookiebot, OneTrust, Complianz, and CookieYes so checkout security challenges and privacy consent banners appear immediately without user interaction.
  • Multilingual Switchers (ESSENTIAL): Client-side and hybrid language switchers from TranslatePress, WPML, Weglot, and GTranslate stay responsive immediately on arrival.
  • Entrance Animations & Preloader Guards (EXTENDED_GUARD_PATTERN): Pages containing theme preloaders or scroll-triggered visibility classes (elementor-invisible, data-aos, data-sal) receive automatic protection so above-the-fold headlines and hero cards never remain stuck at opacity: 0.
  • CSP Header Inspection (CspPolicy.php): Before injecting its lightweight interaction listener, KadiCache inspects active Content-Security-Policy headers. If strict script-src rules forbid inline bootstrap execution without a dynamic nonce, KadiCache gracefully abstains rather than breaking page interactivity.
FIG 01Granular script URL, handle, inline snippet, and page-path exclusion drawers inside WP Admin -> KadiCache -> CSS & JavaScriptZoom 2x

Configuring Minify, Defer & Delay Exclusions in WP Admin -> KadiCache#

Every JavaScript control inside WP Admin -> KadiCache -> CSS & JavaScript is isolated so you can tune individual scripts or landing pages in seconds without turning off sitewide optimization:

  1. Minify JavaScript Files (minify_js_enabled): Strips comments and whitespace from local JavaScript files while automatically skipping pre-minified *.min.js bundles so CPU cycles are never wasted re-compressing vendor libraries.
  2. Delay Execution Trigger Mode (delay_js_mode): Choose strict interaction-only holding for the highest Lighthouse performance score, or enable a gentle fallback timeout when passive wallboard or analytics sessions must fire even if a visitor reads without scrolling.
  3. Delay JavaScript Exclusions (delay_js_exclusions): Enter one rule per line matching a script filename (custom-slider.js), WordPress script ID (#my-calculator-js), external domain (challenges.cloudflare.com), or unique inline variable name (initCustomHeader). Matched scripts execute normally while all remaining third-party tags stay delayed.
  4. Excluded JavaScript Page Paths (delay_js_excluded_paths): Bypass Delay JS on specific routes such as /custom-configurator/* or /mortgage-calculator/ while keeping Page Caching, Cloud Remove Unused CSS, and Media Lazyload active. Individual posts and pages can also toggle Delay JS off directly from the Gutenberg Block Editor sidebar or the Frontend Admin Bar.

Step-by-Step Verification & Troubleshooting Workflow#

After enabling Defer or Delay Until Interaction, run this 60-second verification checklist before closing WP Admin:

  1. Test Logged-Out Incognito Arrival (Hands Off Mouse/Trackpad): Open your homepage, a category archive, and a single WooCommerce product page in a fresh Incognito window without moving the cursor. Confirm the header logo, navigation bar, hero headline, and product gallery look complete before any interaction.
  2. Verify First-Tap Responsiveness: Tap the mobile hamburger menu, open the search drawer, switch product variations, and open the mini-cart. Delayed UI handlers prioritize interactive readiness ahead of low-priority marketing beacons.
  3. Compare Cached vs Uncached in PageSpeed Lab: Open WP Admin -> KadiCache -> Core Web Vitals -> PageSpeed & CrUX Lab (Built-In RUM & PageSpeed Insights) and run Compare Cached vs Uncached on Mobile to verify Total Blocking Time (TBT) drops toward 0 ms and third-party bootup warnings disappear.
  4. Isolate Any Custom Theme Script in 10 Seconds: If a bespoke theme widget needs immediate execution on page load, paste its filename fragment into Delay JavaScript Exclusions, click Save & Purge, and re-test—keeping 95% of your third-party tag weight off the main thread. For full rule syntax, read our Delay JS & Exclusions Guide and explore all Lighthouse remedies in the PageSpeed Audits Hub.
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/DelayJsOptimizer.phpapps/wordpress-plugin/src/Optimization/Scripts/DelayScriptClassifier.phpapps/wordpress-plugin/src/Optimization/ScriptOptimizer.phpapps/wordpress-plugin/src/Optimization/CspPolicy.phpapps/wordpress-plugin/src/Optimization/ConsentScripts.php

Technical FAQ

What is the difference between Defer JavaScript and Delay Until Interaction?

Defer JavaScript downloads scripts in parallel during page load and executes them in DOM order right after HTML parsing finishes. Delay Until Interaction holds non-essential scripts completely out of main-thread execution until the visitor scrolls, taps, clicks, or moves the cursor, reducing initial Total Blocking Time (TBT) toward 0 ms.

Will Delay Until Interaction break my WooCommerce product image gallery or Add to Cart buttons?

No. KadiCache automatically protects WooCommerce single-product gallery scripts (wc-single-product, zoom, flexslider, photoswipe), Stripe/PayPal payment SDKs, and cart fragment updates so shoppers can browse photos and add items on their very first tap.

How does Delay JS handle GDPR cookie consent banners like Cookiebot, OneTrust, or Complianz?

ConsentScripts.php detects major consent management platforms automatically and keeps their banner scripts active on initial load so visitors always see required privacy choices immediately upon landing.

What happens if a visitor already has items in their WooCommerce cart?

By default, KadiCache prioritizes instant interactive cart/checkout behavior for active shoppers. If your store loads heavy third-party chat or tracking scripts that slow down browsing shoppers, you can enable Keep delaying scripts for shoppers inside WP Admin -> KadiCache -> CSS & JavaScript.

How do I exclude one specific inline script or calculator without disabling Delay JS sitewide?

Either add a unique string from that script (such as its function/variable name or script filename) into Delay JavaScript Exclusions in WP Admin -> KadiCache -> CSS & JavaScript, or add the HTML attribute data-kadicache-no-delay to the <script> tag or its parent container.

Does KadiCache Delay JS work safely on sites with strict Content-Security-Policy (CSP) headers?

Yes. CspPolicy.php inspects active Content-Security-Policy headers before modifying script execution and respects strict script-src policies so KadiCache never triggers browser CSP errors that would block site interactivity.