Fix WooCommerce Cart Fragments (wc-ajax) Safely
Stop wc-ajax=get_refreshed_fragments from stalling WooCommerce pages without breaking classic mini-carts or block drawers.

- Blindly dequeuing
wc-cart-fragmentsbreaks header cart badges the moment a shopper adds a product and navigates back to a cached category page. - KadiCache Smart Cart mode gates
#wc-cart-fragments-jsbehind a lightweight client check (#kadicache-cart-fragments-gate) and a non-secretkadicache_cartsession-expiry hint cookie. - Browse-only visitors (typically 85%–94% of mobile storefront traffic) trigger zero
/?wc-ajax=get_refreshed_fragmentsPHP boots while active shoppers keep instant cart counters.
Table of Contents (14 sections)
- Anatomy of the wc-ajax=get_refreshed_fragments Bottleneck
- Tracing What Happens Inside PHP During a Single Fragment Call
- Why Naive wp_dequeue_script('wc-cart-fragments') Snippets Fail in Production
- 1. Frozen Header Badges on Cached Pages
- 2. Broken Script Dependency Chains in Commercial Themes
- 3. Content Security Policy and Custom Inline Callbacks
- Classic jQuery Fragments vs Modern WooCommerce Interactivity API Mini-Carts
- How KadiCache Smart Cart Mode Solves Both Sides Cleanly
- Step 1: The Non-Secret kadicache_cart Expiry Hint Cookie
- Step 2: Dependency Graph & Foreign-Inline Qualification
- Step 3: Client-Side Gate (#kadicache-cart-fragments-gate) + Store API Cookie Sync
- Keeping Delay JavaScript Safe for Active Shoppers
- Step-by-Step Verification in Chrome DevTools and curl
- When Should You Choose original vs smart vs off?
WooCommerce cart fragments (/?wc-ajax=get_refreshed_fragments) remain the single most expensive hidden request on cached WordPress stores. Even when your HTML document arrives from advanced-cache.php in 4.4 milliseconds, a single unguarded fragment script wakes full WordPress core, MySQL, and active WooCommerce extensions for 450 ms to 1,400 ms on every cold mobile visit.
Anatomy of the wc-ajax=get_refreshed_fragments Bottleneck#
Open Chrome DevTools on a stock WooCommerce storefront, clear site data, and reload any product or category archive. Watch the Network waterfall right after DOMContentLoaded. You will see cart-fragments.min.js inspect sessionStorage for wc_fragments_*; finding nothing on a first visit, it immediately dispatches an uncached XHR POST request to /?wc-ajax=get_refreshed_fragments.
Why did WooCommerce engineers build this mechanism in the first place? Because full-page HTML caching and personalized header mini-carts pull in opposite directions. When EarlyRequestServer.php or Cloudflare Edge serves a shared cached HTML document to 5,000 guests, the server cannot bake Shopper A's three cart items into that shared HTML without leaking Shopper A's cart summary to Shopper B.
WooCommerce solved that caching conflict by shipping an empty $0.00 (0 items) mini-cart shell inside the HTML document and forcing every single visitor's browser to phone home via AJAX to ask PHP: "Do I have anything in my cart right now?"
| Traffic Cohort on Typical Store | Share of Total Pageviews | Needs Live Cart Fragment HTML? | Default WooCommerce Behavior | KadiCache Smart Cart Behavior |
|---|---|---|---|---|
| First-time anonymous browser (empty cart) | 68% – 78% | No | Fires uncached wc-ajax PHP boot | 0 wc-ajax requests (stays static) |
| Returning browser (empty cart, fresh tab) | 14% – 18% | No | Re-fires wc-ajax when sessionStorage clears | 0 wc-ajax requests |
| Active shopper with >= 1 item in cart | 6% – 14% | Yes | Fires wc-ajax + updates sessionStorage | Refreshes mini-cart cleanly via gated loader |
Shopper on /cart/ or /checkout/ | 2% – 5% | Handled by page | Full dynamic PHP render | Bypasses page cache (X-KadiCache-Reason) |
Across production WooCommerce telemetry, roughly 85% to 94% of public pageviews belong to visitors with an empty cart. Booting 45+ plugins, running tax and shipping hooks, and querying MySQL for the 90% of visitors who have never clicked Add to Cart wastes PHP-FPM workers and stalls mobile main-thread responsiveness right as the shopper starts scrolling.
Tracing What Happens Inside PHP During a Single Fragment Call#
Many developers assume /?wc-ajax=get_refreshed_fragments runs a tiny isolated SQL query. In reality, WC_AJAX::get_refreshed_fragments() executes after wp-load.php has already initialized every active WordPress plugin, theme functions.php hooks, currency switchers, membership rules, and woocommerce_init listeners.
Once inside WC_AJAX::get_refreshed_fragments(), WooCommerce executes woocommerce_mini_cart(), captures output buffering, runs apply_filters('woocommerce_add_to_cart_fragments', $fragments), computes WC()->cart->get_cart_for_session(), and serializes every registered DOM selector back as JSON. On a store running 35 plugins without a persistent object cache, that single XHR call consumes 42 MB to 96 MB of PHP RAM and 60 to 140 SQL queries.
Now imagine a Meta or TikTok ad campaign sending 300 concurrent mobile visitors per minute to /product/winter-boots/. Your page cache handles the 300 HTML documents in 4 milliseconds with 0% CPU—and then one second later, all 300 phones fire POST /?wc-ajax=get_refreshed_fragments simultaneously, exhausting pm.max_children in PHP-FPM and triggering 502 Bad Gateway errors at checkout!
Why Naive wp_dequeue_script('wc-cart-fragments') Snippets Fail in Production#
Search any WordPress forum for woocommerce cart fragments and you will find hundreds of five-line functions.php snippets calling wp_dequeue_script('wc-cart-fragments') on every front-end template. That shortcut produces an immediate synthetic score bump—and then quietly damages conversion rates in three specific ways.
1. Frozen Header Badges on Cached Pages#
Suppose a visitor lands on /product/espresso-grinder/, clicks Add to Cart (which uses /?wc-ajax=add_to_cart on archive cards or a form POST on single product templates), and then clicks the store logo to return to /. Because / is served from page cache or browser disk cache with 0 items in the header HTML—and wc-cart-fragments was dequeued—the header badge drops back to 0.
Shoppers assume their item vanished, click back to add it a second time, and arrive at /checkout/ with duplicate quantities—or abandon the store altogether thinking the cart is broken.
2. Broken Script Dependency Chains in Commercial Themes#
Popular WooCommerce themes (Astra Pro, Flatsome, WoodMart, Porto, Kadence Shop Kit, Shoptimizer) and side-cart drawers register their own drawer JavaScript with ['jquery', 'wc-cart-fragments'] inside WP_Scripts. When you dequeue wc-cart-fragments unconditionally, WordPress core silently drops every downstream script that declared it as a dependency.
Off-canvas slide-out cart drawers stop opening on tap, sticky mobile add-to-cart bars freeze, and free-shipping progress bars fail without logging a single PHP error.
3. Content Security Policy and Custom Inline Callbacks#
Payment FraudNet modules, multi-currency switchers (CURCY, FOX, WCML), and analytics pixels frequently attach inline before or after scripts to the wc-cart-fragments handle via wp_add_inline_script(). Stripping the handle blindly discards those attached callbacks or violates strict nonce and Subresource integrity attributes.
Classic jQuery Fragments vs Modern WooCommerce Interactivity API Mini-Carts#
WooCommerce 8.x through 10.x introduced a major architectural split that older optimization plugins still misunderstand. Storefronts today use one of three distinct cart surfaces:
| Cart Surface Architecture | Underlying Browser Transport | DOM / Script Signature | How KadiCache Handles It |
|---|---|---|---|
| Classic Theme Mini-Cart (Astra, Flatsome, Storefront) | jQuery wc-cart-fragments -> /?wc-ajax=get_refreshed_fragments | div.widget_shopping_cart_content + #wc-cart-fragments-js | Gates #wc-cart-fragments-js until kadicache_cart or woocommerce_items_in_cart exists |
Gutenberg Mini-Cart Block (iapi) | WordPress Interactivity API -> /wp-json/wc/store/v1/cart | .wc-block-mini-cart (data-wp-interactive) | Marks unneeded classic fragment tags inert + syncs Store API cookies & #kadicache-mini-cart-status |
| Hybrid / Mixed Surface (Block Mini-Cart + Classic Third-Party Badge) | Both Store API and woocommerce_add_to_cart_fragments | Both .wc-block-mini-cart and custom theme selector | Detects mixed surface in CartFragmentQualification.php and keeps both consistent |
Look at CartFragmentQualification::supportsRefresh() inside KadiCache Free Core: instead of assuming every store uses the 2017 jQuery widget, it inspects registered woocommerce_add_to_cart_fragments selectors alongside WooCommerceMiniCartBlock::hasNativeSurface($html) to classify the page cleanly as classic, iapi, or mixed.
How KadiCache Smart Cart Mode Solves Both Sides Cleanly#
Inside WP Admin -> KadiCache -> CSS & JavaScript -> Commerce & Smart Cart, KadiCache implements a deterministic three-part state machine (Integrations/Plugins/WooCommerceCartFragments.php) paired with our WooCommerce & Multilingual Caching engine.
Step 1: The Non-Secret kadicache_cart Expiry Hint Cookie#
WooCommerce's authoritative session cookie (wp_woocommerce_session_<hash>) is flagged HttpOnly, meaning browser JavaScript cannot inspect document.cookie to verify whether a server session is still alive. Meanwhile, woocommerce_items_in_cart is a browser-session cookie without an explicit expiration timestamp, so mobile browsers suspending tabs in the background frequently desynchronize it from the real server session.
Inside WooCommerceCartFragments::rememberCart(), KadiCache hooks woocommerce_set_cart_cookies, woocommerce_cart_emptied, woocommerce_cart_item_removed, and rest_post_dispatch on /wc/store/v1/cart:
// Verified logic from WooCommerceCartFragments::rememberCart()
if (WC()->cart->is_empty()) {
if (isset($_COOKIE['kadicache_cart'])) {
wc_setcookie('kadicache_cart', '', time() - HOUR_IN_SECONDS, is_ssl());
unset($_COOKIE['kadicache_cart']);
}
return;
}
// Stores ONLY the integer Unix expiry timestamp — zero PII, zero session tokens
wc_setcookie('kadicache_cart', (string) $expires, $expires, is_ssl());Notice two critical properties of that cookie:
- Zero PII or Session Material:
kadicache_cartstores only an integer Unix expiration timestamp (such as1795581200), never user IDs, email hashes, item SKUs, or session keys.
- 100% Shared Cache Hit Rate for Browsers: Empty-cart guests never receive
kadicache_cartat all, and when an active shopper removes their final cart item (via classic form POST or/wc/store/v1/cartREST API),clearEmptyCartHint()expires the cookie immediately so future navigations return to zero-AJAX static browsing.
Step 2: Dependency Graph & Foreign-Inline Qualification#
Before rewriting or skipping any script tag, CartFragmentQualification.php audits the live WP_Scripts dependency graph and final HTML buffer:
- Dependency Walk (
CartFragmentQualification::anyDependsOn()): Traversesqueue,done,to_do, andin_footerup to 2,000 handles to verify whether any theme or plugin script depends onwc-cart-fragments.
- Foreign Inline Guard (
CartFragmentQualification::foreignInline()): Inspects$registered->extra['before']and$registered->extra['after']so custom third-party inline hooks are never silently dropped.
- CSP & Subresource Integrity Respect: In
WooCommerceCartFragments::rewriteHtml(), if the response sends aContent-Security-Policyheader/meta tag or attachesnonceorintegrityattributes to#wc-cart-fragments-js, Smart Cart leaves the tag unmodified rather than risking a browser CSP violation.
Step 3: Client-Side Gate (#kadicache-cart-fragments-gate) + Store API Cookie Sync#
When the page qualifies for Smart Cart gating, KadiCache transforms <script id="wc-cart-fragments-js" src="..."> into an inline gate (id="kadicache-cart-fragments-gate" carrying data-kadicache-original-src) paired with #kadicache-cart-refresh.
When an empty-cart visitor loads the page, the gate checks document.cookie in under 0.2 milliseconds. Seeing no woocommerce_cart_hash, no woocommerce_items_in_cart, and no unexpired kadicache_cart timestamp, it exits cleanly—zero cart-fragments.min.js download, zero jQuery execution, and zero /?wc-ajax=get_refreshed_fragments PHP load.
The instant that visitor clicks Add to Cart, or visits in a browser carrying an active cart cookie, the gate loads the original WooCommerce script on demand and updates every registered selector in woocommerce_add_to_cart_fragments. Additionally, refreshStoreCartCookies() hooks rest_post_dispatch on /wc/store/v1/cart/(add-item|update-item|remove-item|apply-coupon). Headless and block Store API mutations keep native cart cookies synchronized before PHP flushes the JSON body.
Keeping Delay JavaScript Safe for Active Shoppers#
What happens when you pair Smart Cart with JavaScript Defer & Delay JS to lower mobile Total Blocking Time (TBT) and Interaction to Next Paint (INP)?
Look at WooCommerceCartFragments::delayExclusions() in Free Core:
- If you prefer
cart_fragments_mode = 'original'alongsidekeep_delaying_for_shoppers, KadiCache automatically appendswc-cart-fragments-jstokadicache_delay_js_exclusionsso an active shopper's header cart refreshes immediately without waiting for a scroll or tap.
- In
smartmode,#kadicache-cart-refreshand#kadicache-mini-cart-statusemitdata-kadicache-no-delayanddata-kadicache-independent. Empty-cart guests execute almost zero JavaScript on load, while active shoppers get immediate cart badge updates even while Google Tag Manager, Meta Pixel, chat widgets, and below-the-fold carousels stay delayed.
Step-by-Step Verification in Chrome DevTools and curl#
Never trust any WooCommerce optimization without testing both the empty-cart guest journey and the active-shopper journey. Run this two-minute check after enabling Smart Cart in our WooCommerce setup documentation:
# 1. Warm a product URL and verify a sub-10ms Early Cache HIT for anonymous guests
curl -sI https://example.com/product/sample-hoodie/ | grep -iE "x-kadicache|server-timing|cache-control"
# Expected response headers:
# X-KadiCache: HIT
# Server-Timing: kc;desc="early_hit"Next, verify the browser gate and zero wc-ajax behavior inside an Incognito Chrome window:
- Open a fresh Incognito tab, open DevTools -> Network, and type
wc-ajaxin the filter box.
- Navigate across
/,/shop/, and/product/sample-hoodie/without adding any item to the cart. Confirm 0 requests appear forwc-ajax=get_refreshed_fragments.
- Open DevTools -> Elements and search for
kadicache-cart-fragments-gate(classic themes) orkadicache-mini-cart-status(block themes) to verify the non-blocking gate is active.
- Click Add to Cart, verify the header cart badge increments to
1, and click back to/. Confirm/still loads from cache while the header badge immediately reflects1item andApplication -> Cookiesdisplayskadicache_cart.
- Remove the item from the mini-cart drawer and reload
/shop/. Confirmkadicache_cartis cleared andwc-ajax=get_refreshed_fragmentsgoes silent again.
When Should You Choose original vs smart vs off?#
Use smart (recommended) on virtually all classic, block, and page-builder WooCommerce stores (Astra, Kadence, Flatsome, WoodMart, GeneratePress, Blocksy, Storefront, Hello Elementor). Choose off only on catalog-only or direct-to-checkout stores that have no header cart icon or mini-cart drawer anywhere in the layout. Reserve original only for custom-coded headless themes that poll private AJAX endpoints outside WooCommerce's standard fragment and Store API contracts.
Frequently Asked Engineering Questions
Why does /?wc-ajax=get_refreshed_fragments bypass every page cache?
What happens if I dequeue wc-cart-fragments completely with a functions.php snippet?
Does WooCommerce 9.x / 10.x still use cart fragments if my theme uses the Gutenberg Mini-Cart block?
Is any customer PII stored inside the kadicache_cart hint cookie?
Creator of KadiCache’s Early PHP Drop-In, 7-Driver Object Cache Engine, Cloud Remove Unused CSS, and Zero-CLS Lazy Render pipeline.
Bounded currency/language cache buckets, 8 Express Wallets, and 6 wishlist integrations.
Exact cookie rules, mini-cart qualification checks, and X-KadiCache-Reason headers.
Why synchronous jQuery cart hydration during page load blocks mobile tap responsiveness.
Keep origin PHP workers free by serving Early HTML snapshots in 4.4 ms.