Using MutationObserver to mimic AJAX in Shopify Themes
MutationObserver is a super handy tool in the front-ender’s toolbox – especially when it comes to Shopify themes. This is how I used it with the Streamline theme from Archetype – but it can certainly be applied to a bunch of other themes too.
Here’s how I created a countdown to free shipping using the Web API.
The end goal for this task is creating a countdown for free shipping.
Here’s the business logic: our customer spends $55, and her shipping is free. Our merchant needs a nice little message near the cart total showing the customer how much more they should spend to get free shipping.
The issue in this case was that none of these will work.
This is because Archetype returns a Product Object on the product added to Ajax cart.
The product object won’t help us… as it won’t give us the total which comes from the cart object, and the cart updated event will only work when the customer actually changes the quantity of a cart item from the cart page. Bummer!
Luckily, in the DOM, we have the cart price being updated dynamically via AJAX without a page refresh. Nice!
So, customer adds a product – price updates, and we have something to work with – a source of truth, if you will.
Here’s our markup:
Our MutationObserver will watch the StickySubtotal span, and anytime it updates, we’ll run some functions to create our countdown and update the DOM in real-time. First, let’s add the markup to show the message:
Now that we’ve got all of that brewing in the DOM, (and working on refresh), we can add our MutationObserver and begin updating the countdown.
And that’s it! I’m sure there’s other ways to achieve this, and I’d love to hear how you’d approach this problem.
For now, we have a unique way to observe the cart object’s subtotal and have created a handy little message that engages our customer and upsells to free shipping.