Include Liquid Ajax Cart to the Shopify theme code or import the package from npm. In both cases it will be globally available on the website.
Upload the liquid-ajax-cart-v2.2.0.js file to your Shopify theme’s asset folder and include it in the layout/theme.liquid template.
Provide the cart data in the JSON format within the script tag
with the data-ajax-cart-initial-state attribute so that
Liquid Ajax Cart knows the user cart state.
If Liquid Ajax Cart doesn’t find the cart JSON, it will make a Shopify Cart API Ajax request to get the cart state.
{% comment %} Somewhere in layout/theme.liquid {% endcomment %}
<script type="application/json" data-ajax-cart-initial-state>
{{ cart | json }}
</script>
<script type="module">
import '{{ "liquid-ajax-cart-v2.2.0.js" | asset_url }}';
</script>
Download Liquid Ajax Cart from npm :
npm install liquid-ajax-cart
Import the library:
import "liquid-ajax-cart";
Provide the cart data in the JSON format within the script tag
with the data-ajax-cart-initial-state attribute so that
Liquid Ajax Cart knows the user cart state.
If Liquid Ajax Cart doesn’t find the cart JSON, it will make a Shopify Cart API Ajax request to get the cart state.
{% comment %} Somewhere in layout/theme.liquid {% endcomment %}
<script type="application/json" data-ajax-cart-initial-state>
{{ cart | json }}
</script>
<script src="{{ 'my-bundle.min.js' | asset_url }}" defer="defer"></script>
Once Liquid Ajax Cart is loaded and initialized,
the js-ajax-cart-init CSS class will be added to the html tag.
If you want to run your JavaScript once Liquid Ajax Cart is initialized,
check the liquidAjaxCart.init property
and listen for the liquid-ajax-cart:init event:
function runWhenInit() {
console.log("The current cart state is: ", window.liquidAjaxCart.cart);
}
if (window.liquidAjaxCart?.init) {
// if Liquid Ajax Cart is already initialized
runWhenInit();
} else {
// wait for Liquid Ajax Cart to be initialized
document.addEventListener("liquid-ajax-cart:init", runWhenInit);
}
The detailed explanation on how to interact with Liquid Ajax Cart using JavaScript is in the “Lifecycle, events, API” guide.