Guide

Lifecycle, events, API

Liquid Ajax Cart provides methods for executing Shopify Cart API Ajax requests, as well as properties and events to extend functionality.

Initialization

Once Liquid Ajax Cart is loaded, it does the following:

  • Creates the liquidAjaxCart object

    The liquidAjaxCart object is defined as a property of the window object to be accessible from everywhere. Once created, it has:

    • the init property — reflects the initialization status of the library, which is false at the moment.
    • the conf() method — lets you set configuration parameters.
    layout/theme.liquid
    <script type="module">
      import '{{ "liquid-ajax-cart-v2.1.1.js" | asset_url }}';
      
      // Is Liquid Ajax Cart initialized: false
      console.log("Is Liquid Ajax Cart initialized: ",  window.liquidAjaxCart.init);
      
      // Configuration function is available right after import
      window.liquidAjaxCart.conf('updateOnWindowFocus', false);
    </script>
  • Gets the cart state

    Firstly, Liquid Ajax Cart attempts to retrieve the cart state data from the first found script element with the data-ajax-cart-initial-state attribute, which is supposed to contain the cart data in the JSON format, as shown in the “Installation” guide. If there is no such element found, Liquid Ajax Cart performs a Shopify Cart API Ajax request to retrieve the cart state data.

  • Updates the liquidAjaxCart object

    When the cart state data is received, the init property becomes true. Also, Liquid Ajax Cart populates the liquidAjaxCart object with the following methods and properties:

    • get() — makes a Shopify Cart API GET /cart.js Ajax request;
    • add() — makes a POST /cart/add.js request;
    • change() — makes a POST /cart/change.js request;
    • update() — makes a POST /cart/update.js request;
    • clear() — makes a POST /cart/clear.js request;
    • cart — keeps the current cart state data;
    • processingtrue if there is a request in progress now.
  • Adds the js-ajax-cart-init CSS class

    The js-ajax-cart-init CSS class is added to the html tag.

  • Event

    Triggers the liquid-ajax-cart:init event

    Since most of the liquidAjaxCart methods and properties are available only after the initialization, use the liquid-ajax-cart:init event along with the liquidAjaxCart.init property when your code depends on Liquid Ajax Cart and should be executed as soon as the library is fully available:

    assets/script.js
    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);
    }

Shopify Cart API requests

Liquid Ajax Cart provides the methods get, add, change, update, clear of the liquidAjaxCart object to perform Shopify Cart API Ajax requests. Use these methods rather than fetch or any other way of sending requests. Otherwise, Liquid Ajax Cart won’t update the cart-related content on the page.

Liquid Ajax Cart uses these methods as well when performing Shopify Cart API Ajax requests.

For example, when a user clicks an “Add to cart” button in a product form, wrapped with the <ajax-cart-product-form> custom tag, Liquid Ajax Cart calls the liquidAjaxCart.add() method in order to performs a Shopify Cart API /cart/add.js Ajax request.

Queue of requests

When one of the methods get, add, change, update, clear of the liquidAjaxCart object is called, Liquid Ajax Cart adds a Shopify Cart API Ajax request to the Queue of requests.

Once the Queue isn’t empty, Liquid Ajax Cart switches to the “processing requests” mode and executes requests according to their order until the Queue is empty.

When Liquid Ajax Cart is in the “processing requests” mode, the liquidAjaxCart.processing property is true and the js-ajax-cart-processing CSS class is added to the html tag so that you can show a loading indicator.

Queue lifecycle

When one of the methods get, add, change, update, clear of the liquidAjaxCart object is called, Liquid Ajax Cart adds a Shopify Cart API Ajax request to the Queue of requests.

If the Queue isn’t empty when a new request is getting added, that means Liquid Ajax Cart is already in the “processing requests” mode, and the new request will be added to the end of the Queue and executed when the previous requests are finished:

#1: [/cart/change.js — executing]
#2: [/cart/add.js — new added request]

Each request is executed according to the Request lifecycle.

Switching from the “idle” to the “processing requests” mode

If the Queue is empty when a new request is getting added, that means Liquid Ajax Cart is in the “idle” mode and has to switch to the “request processing” mode. Liquid Ajax Cart does the following:

  • Adds the request to the Queue

    As the Queue has been empty, the new request will be the first:

    #1: [/cart/add.js — new added request]
  • Sets liquidAjaxCart.processing to true

    Since Liquid Ajax Cart was in the “idle” mode, the liquidAjaxCart.processing property was false. Now the Queue of requests has a request to execute, and the liquidAjaxCart.processing property becomes true.

  • Adds the js-ajax-cart-processing CSS class

    The js-ajax-cart-processing CSS class is added to the html tag;

  • Event

    Triggers the liquid-ajax-cart:queue-start event

    As Liquid Ajax Cart is about to start executing requests from the Queue, the liquid-ajax-cart:queue-start event is fired.

  • Executes requests

    Liquid Ajax Cart executes the first request in the Queue:

    #1: [/cart/add.js — executing]

    If one of the methods get, add, change, update, clear of the liquidAjaxCart object is called while the request is executing, Liquid Ajax Cart will add the new requests to the end of the Queue and execute them until the Queue is empty:

    #1: [/cart/add.js — executing]
    #2: [/cart/change.js]

    Each request is executed according to the Request lifecycle.

  • Sets liquidAjaxCart.processing to false

    Once all requests are executed and the Queue is empty, Liquid Ajax Cart is switching back to the “idle” mode, thus it sets liquidAjaxCart.processing property was false.

  • Removes the js-ajax-cart-processing CSS class

    The js-ajax-cart-processing CSS class is removed from the html tag;

  • Event

    Triggers the liquid-ajax-cart:queue-end event

    As Liquid Ajax Cart has executed all the requests from the Queue and it is switching back to the “idle” mode, the liquid-ajax-cart:queue-end event is fired.

Request lifecycle

Liquid Ajax Cart does the folowing when performs a Shopify Cart API Ajax request:

  • Creates a Request state object

    Liquid Ajax Cart creates a Request state object for each Shopify Cart API request. When created, the object has the following properties:

    {
      "endpoint": "/cart/add.js",
      "requestBody": {…},
      "requestType": "add",
      "info": {…}
    }
  • Prepares the request body

    Liquid Ajax Cart adds the sections parameter to the request body with the IDs of the Shopify sections that contain data-ajax-cart-section elements. Shopify will return the re-rendered HTML of the sections in response to the request. (Bundled section rendering).

    The modified requestBody property of the Request state object:

    {
      "endpoint": "/cart/add.js",
      "requestBody": {
        "items": [
          {
            "id": 40934235668668,
            "quantity": 1
          }
        ],
        "sections": "my-ajax-cart"
      },
      "requestType": "add",
      "info": {…}
    }
  • Hides errors in the the data-ajax-cart-errors elements.

    Liquid Ajax Cart empties the data-ajax-cart-errors elements related to the request. For example, if the request was initiated by a product form, only the data-ajax-cart-errors element that belongs to the form, will be emptied.

  • Event

    Triggers the liquid-ajax-cart:request-start event

    The liquid-ajax-cart:request-start event is fired a moment before the request is performed. You can read, modify or cancel the request in your event listener.

  • If not cancelled
    Sends the request to Shopify

    Liquid Ajax Cart performs the request if it isn’t cancelled (the info.cancel property of the Request state object isn’t true). Otherwise, this step is skipped.

    If the request is successful but the response doesn’t have the cart state object (the /cart/add.js endpoint is the case), or if the response doesn’t have HTML of all Shopify sections needed, Liquid Ajax Cart performs an additional /cart/update.js request to get the data.

  • Updates the Request state object

    Liquid Ajax Cart populates the Request state object according to the request result — the responseData / extraResponseData / fetchError properties:

    {
      "endpoint": "/cart/add.js",
      "requestBody": {…},
      "requestType": "add",
      "info": {…},
      "responseData": {
        "ok": true,
        "status": 200,
        "body": {…}
      },
      "extraResponseData": {…} 
    }
  • Callback
    Calls the firstCallback function

    When you directly call one of the methods get, add, change, update, clear of the liquidAjaxCart object, you can define the firstCallback function.

  • If request is successful
    Replaces the data-ajax-cart-section elements

    If the request is successful, Liquid Ajax Cart retrieves the re-rendered HTML of the data-ajax-cart-section elements from the response. It then replaces the current data-ajax-cart-section elements’ outer HTML with the new one.

  • If request is failed
    Shows errors in the data-ajax-cart-errors elements

    If the request is failed, Liquid Ajax Cart inserts the error message to the related data-ajax-cart-errors element.

  • If request is successful
    Saves the cart state in liquidAjaxCart.cart property

    If the request is successful, Liquid Ajax Cart extracts the cart state data from the response and stores it within the liquidAjaxCart.cart property.

  • Syncs DOM with the cart state

    The data-ajax-cart-bind elements HTML, the data-ajax-cart-quantity-input and data-ajax-cart-property-input input values, as well as the js-ajax-cart-empty and js-ajax-cart-not-empty CSS classes, get updated according to the cart state data.

  • Event

    Triggers the liquid-ajax-cart:request-end event

    The liquid-ajax-cart:request-end is the only event that is fired right after a request is executed, the cart state (liquidAjaxCart.cart) is updated and the cart-related content is re-rendered.

  • Callback
    Calls lastCallback function

    When you directly call one of the methods get, add, change, update, clear of the liquidAjaxCart object, you can define the lastCallback function.