Skip to main content
KadiCache
Engineering Journal · WooCommerce9 min read1,882 wordsVerified 2026-11-23

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.

Blocking slow wc-ajax cart fragment requests behind a shield to serve a 4ms HIT WooCommerce storefront
0.000 Layout Shift14 Sections✓ Verified
⚡ Executive Summary · 30-Second Spec100% Code-Verified
WP Admin Path
WP Admin -> KadiCache -> CSS & JavaScript -> Commerce & Smart Cart
Measured Impact
0 uncached wc-ajax hits for empty-cart guests · < 5 ms Early HTML HIT
DevTools Proof Marker
script#kadicache-cart-fragments-gate | cookie: kadicache_cart
  • Blindly dequeuing wc-cart-fragments breaks 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-js behind a lightweight client check (#kadicache-cart-fragments-gate) and a non-secret kadicache_cart session-expiry hint cookie.
  • Browse-only visitors (typically 85%–94% of mobile storefront traffic) trigger zero /?wc-ajax=get_refreshed_fragments PHP boots while active shoppers keep instant cart counters.
Table of Contents (14 sections)

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 StoreShare of Total PageviewsNeeds Live Cart Fragment HTML?Default WooCommerce BehaviorKadiCache Smart Cart Behavior
First-time anonymous browser (empty cart)68% – 78%NoFires uncached wc-ajax PHP boot0 wc-ajax requests (stays static)
Returning browser (empty cart, fresh tab)14% – 18%NoRe-fires wc-ajax when sessionStorage clears0 wc-ajax requests
Active shopper with >= 1 item in cart6% – 14%YesFires wc-ajax + updates sessionStorageRefreshes mini-cart cleanly via gated loader
Shopper on /cart/ or /checkout/2% – 5%Handled by pageFull dynamic PHP renderBypasses 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!

FIG 01Smart WooCommerce Cart Fragments eliminates uncached wc-ajax=get_refreshed_fragments requests for browsing guests while syncing active carts.Zoom 2x

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 ArchitectureUnderlying Browser TransportDOM / Script SignatureHow KadiCache Handles It
Classic Theme Mini-Cart (Astra, Flatsome, Storefront)jQuery wc-cart-fragments -> /?wc-ajax=get_refreshed_fragmentsdiv.widget_shopping_cart_content + #wc-cart-fragments-jsGates #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_fragmentsBoth .wc-block-mini-cart and custom theme selectorDetects 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.

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:

PHP
// 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_cart stores only an integer Unix expiration timestamp (such as 1795581200), never user IDs, email hashes, item SKUs, or session keys.
  • 100% Shared Cache Hit Rate for Browsers: Empty-cart guests never receive kadicache_cart at all, and when an active shopper removes their final cart item (via classic form POST or /wc/store/v1/cart REST 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()): Traverses queue, done, to_do, and in_footer up to 2,000 handles to verify whether any theme or plugin script depends on wc-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 a Content-Security-Policy header/meta tag or attaches nonce or integrity attributes 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.

FIG 02Consolidated route exclusions, 404/commenter caching, HTTP 304 ETag validators, and edge s-maxage controls in one tab.Zoom 2x

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' alongside keep_delaying_for_shoppers, KadiCache automatically appends wc-cart-fragments-js to kadicache_delay_js_exclusions so an active shopper's header cart refreshes immediately without waiting for a scroll or tap.
  • In smart mode, #kadicache-cart-refresh and #kadicache-mini-cart-status emit data-kadicache-no-delay and data-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:

BASH
# 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:

  1. Open a fresh Incognito tab, open DevTools -> Network, and type wc-ajax in the filter box.
  1. Navigate across /, /shop/, and /product/sample-hoodie/ without adding any item to the cart. Confirm 0 requests appear for wc-ajax=get_refreshed_fragments.
  1. Open DevTools -> Elements and search for kadicache-cart-fragments-gate (classic themes) or kadicache-mini-cart-status (block themes) to verify the non-blocking gate is active.
  1. 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 reflects 1 item and Application -> Cookies displays kadicache_cart.
  1. Remove the item from the mini-cart drawer and reload /shop/. Confirm kadicache_cart is cleared and wc-ajax=get_refreshed_fragments goes 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?
Because WooCommerce sends it as an uncached POST or dynamic wc-ajax endpoint designed to compute personalized cart HTML and session hashes in PHP. Neither Nginx FastCGI, Cloudflare APO, nor advanced-cache.php can serve a static HTML snapshot for that endpoint.
What happens if I dequeue wc-cart-fragments completely with a functions.php snippet?
On any cached page, the header mini-cart stays frozen at 0 items even after a customer adds products to their cart, causing confused shoppers to double-add items or abandon checkout.
Does WooCommerce 9.x / 10.x still use cart fragments if my theme uses the Gutenberg Mini-Cart block?
Modern block themes use the Interactivity API and /wp-json/wc/store/v1/cart instead of classic fragments, unless a third-party plugin enqueues wc-cart-fragments as a script dependency. KadiCache inspects both surfaces automatically inside CartFragmentQualification.php.
Is any customer PII stored inside the kadicache_cart hint cookie?
No. WooCommerceCartFragments::rememberCart() writes only the integer Unix expiration timestamp of the active cart session and clears the cookie immediately when the cart becomes empty.
Verified WordPress Architecture · WooCommerce
Apply these exact optimizations on your WordPress or WooCommerce site in 2 minutes.
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.

Integrations/Plugins/WooCommerceCartFragments.phpIntegrations/Plugins/WooCommerce/CartFragmentQualification.phpIntegrations/Plugins/WooCommerceSession.phpDiagnostics/CartFragmentAdvice.php
Connected Topical Cluster · Continue Deepening Your Setup