What are cart fragments? How WooCommerce updates the cart on a page

Published , by the PrintBlob team.

Cart fragments are the pieces of a WooCommerce page that show the cart, such as the item count in the header and the contents of the mini cart, which WooCommerce sends as fresh HTML after the cart changes, so the page can update them without reloading. Each fragment is a CSS selector and the HTML that replaces the element it names.

They let a classic theme show the right cart on a page that may have been built before the item was added, or cached for everyone.

How they work

  • After an Ajax add to cart, WooCommerce answers with the fragments, and its script replaces each element the selectors name with the new HTML. Then it announces added_to_cart, with the fragments, for themes and plugins to react to.
  • On request, a page can ask for them at WooCommerce’s get_refreshed_fragments address. WooCommerce’s cart-fragments script does that when told the cart changed elsewhere, and keeps the last ones in the browser’s session storage so the next page can show them at once.
  • What is in them depends on the theme and plugins. WooCommerce’s own fragment is the mini cart widget’s contents, div.widget_shopping_cart_content; themes add their header count and their drawer through a WooCommerce filter.

Fragments and speed

The cart-fragments script used to run on every page and ask the server for fragments, which slowed down shops whose pages were otherwise cached. WooCommerce 7.8 stopped loading it on every page by default; it now loads where the mini cart widget is used. A theme that uses fragments for its header loads it itself.

Fragments and the blocks

WooCommerce’s block-based Mini-Cart does not use fragments: it reads the cart through the Store API. A shop can have both, a block theme’s Mini-Cart and a page builder’s cart widget, on one page, and an add to the cart has to reach both: the fragments for the one, the blocks’ event, or added_to_cart, which the blocks also hear, for the other.

In PrintBlob

After a design is added to the cart, PrintBlob’s designer asks WooCommerce for the refreshed fragments, puts them in place as WooCommerce’s own script does, and announces added_to_cart, since version 1.7.1. More in product designer problems in WooCommerce themes.

Sources