DEV Community

Navneet Raj
Navneet Raj

Posted on • Updated on

Why & How to Disable Ajax Cart Fragments

First of all, the script “wc-cart-fragments” is described by a function called “register_scripts()”. It calls a JS script from the /assets folder and requires JQuery and cookies to be enabled:

'wc-cart-fragments' => array(
'src' => self::get_asset_url( 'assets/js/frontend/cart-fragments' . $suffix . '.js' ),
'deps' => array( 'jquery', 'js-cookie' ),
'version' => WC_VERSION,
),

In the same file, this is the time “wc-cart-fragments” gets called:

self::enqueue_script( 'wc-cart-fragments' );
If we look at the “enqueue_script()” function we’ll find out that our “wc-cart-fragments” script is first registered and then enqueued as per the WordPress documentation

private static function enqueue_script( $handle, $path = '', $deps = array( 'jquery' ), $version = WC_VERSION, $in_footer = true ) {
if ( ! in_array( $handle, self::$scripts, true ) && $path ) {
self::register_script( $handle, $path, $deps, $version, $in_footer );
}
wp_enqueue_script( $handle );
}

If something is “enqueued”, then it can be “dequeued” (similar to add_action() and remove_action() PHP functions).
You have to make sure to call the “dequeue” function AFTER the “enqueue” one, so that it’s been already added and you can remove it (hence the priority = 11 as “wc-cart-fragments” is enqueued at default priority of 10).
Tl;dr:

add_action( 'wp_enqueue_scripts', 'gomahamaya_disable_woocommerce_cart_fragments', 11 );
function gomahamaya_disable_woocommerce_cart_fragments() {
wp_dequeue_script( 'wc-cart-fragments' );
}

Please note that in case you have a header cart widget, this will break the “dropdown cart”. You’ll still be able to see the number of items and the cart total in the header, but on hover you won’t get the items and cart/checkout buttons.
On Business Bloomer, I completely disabled the Cart widget hence it makes sense to use this function.
In case you want to just optimize your homepage and leave the “wc-cart-fragments” on the other website pages, you can use this snippet instead:

add_action( 'wp_enqueue_scripts', 'gomahamaya_disable_woocommerce_cart_fragments', 11 );
function gomahamaya_disable_woocommerce_cart_fragments() {
if ( is_front_page() ) wp_dequeue_script( 'wc-cart-fragments' );

Reference Blog

How To Disable WooCommerce Cart Fragments Ajax - Gomahamaya

Top comments (0)