Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 61 ยท JavaScript, CSS and Design

JavaScript in Themes: Web Components and Events

Write modern Shopify theme JavaScript with custom elements, pub-sub events, module scripts, defer and the theme editor events, without jQuery.

Themes used to ship a pile of jQuery plugins and global functions. Modern Shopify themes do something simpler: they use plain JavaScript, native custom elements (often called web components), a few small shared modules and the events that the browser and the theme editor already provide. The result is less code to download, fewer conflicts with apps, and components that keep working when the merchant edits the page.

This lesson shows how to organize theme JavaScript, how a custom element's lifecycle fits sections, how to let components talk through a tiny publish and subscribe bus, how to load scripts without slowing the page, and how to react to the theme editor's section events. The examples build on Building a Cart Drawer and on the file layout from The Theme File Structure.

Theme files (Liquid and the scripts that ship in assets/) run on a real storefront, so those snippets are read-only here. The live parts run in your browser: one TryIt simulates the custom element lifecycle and the event bus in plain JavaScript, and another uses real custom elements in an HTML preview. This lesson targets current Online Store 2.0 themes and modern browsers.

Why custom elements fit themes

A custom element is an HTML tag you define, such as <quantity-input>. The browser creates your class for every such tag it finds and calls lifecycle methods:

  • constructor() runs when the element is created. Keep it light and do not touch children yet.
  • connectedCallback() runs each time the element is inserted into the document, including when the parser finds it and when JavaScript moves it. This is where you add event listeners.
  • disconnectedCallback() runs when it is removed. This is where you clean up timers, observers and listeners on things outside the element.

Two properties make this a great fit for Shopify. First, registration is global but per tag name: you define quantity-input once and every instance on the page, including ones that arrive later, is upgraded. Second, HTML replacement just works. When the theme editor reloads a section, or your cart drawer swaps in new HTML from the Section Rendering API (see The Section Rendering API and Dynamic Updates), the new elements run connectedCallback automatically. No manual re-initialization like $(document).ready(initSlider) is needed.

JavaScript
// assets/quantity-input.js (read-only example)
class QuantityInput extends HTMLElement {
  connectedCallback() {
    this.input = this.querySelector('input');
    this.addEventListener('click', this.onClick);
  }

  disconnectedCallback() {
    this.removeEventListener('click', this.onClick);
  }

  onClick = (event) => {
    const button = event.target.closest('button[data-step]');
    if (!button) return;
    const step = Number(button.dataset.step);
    const next = Math.max(Number(this.input.min || 0), Number(this.input.value) + step);
    this.input.value = String(next);
    this.input.dispatchEvent(new Event('change', { bubbles: true }));
  };
}

if (!customElements.get('quantity-input')) {
  customElements.define('quantity-input', QuantityInput);
}

The customElements.get guard matters on Shopify: a script can be included twice (a section and a snippet both load it), and defining the same name twice throws an error.

The markup stays plain Liquid and HTML:

LIQUID
<quantity-input class="quantity">
  <button type="button" data-step="-1" aria-label="{{ 'products.quantity.decrease' | t }}">-</button>
  <input type="number" name="quantity" value="1" min="1" inputmode="numeric">
  <button type="button" data-step="1" aria-label="{{ 'products.quantity.increase' | t }}">+</button>
</quantity-input>

Without JavaScript, the field is still a number input the shopper can type in. That is progressive enhancement: the component adds convenience on top of working HTML.

Loading scripts: asset_url, defer and modules

Put theme scripts in assets/ and load them with the asset_url filter (see Shopify Filters):

LIQUID
<script src="{{ 'quantity-input.js' | asset_url }}" defer="defer"></script>

Choose between these loading styles:

Style Behavior
plain <script src> in the head blocks HTML parsing; avoid
defer downloads in parallel, runs after parsing, in order
type="module" deferred by default, supports import, runs once per URL
async runs as soon as it arrives, order not guaranteed; fine for independent scripts

Dawn-style themes load most scripts with defer. Load a script only on pages that need it: a section can include its own <script> tag, or use {% javascript %} (explained in CSS for Themes). Never add a library for something the platform already does: fetch, classList, closest, URLSearchParams, IntersectionObserver, <dialog> and <details> replace most of what jQuery was used for. Performance consequences are covered in Theme Performance and Core Web Vitals.

Talking between components: a tiny event bus

A cart drawer, a header cart count and a free-shipping bar all want to know when the cart changes. Wiring them to each other makes a tangle. Instead, let the component that changes the cart publish an event and let the others subscribe.

The platform already has a bus: DOM events. You can dispatch a CustomEvent on document. Many themes also keep a small publish and subscribe module that works with plain callbacks:

JavaScript
// assets/pubsub.js (read-only example)
const subscribers = {};

export function subscribe(eventName, callback) {
  (subscribers[eventName] ??= []).push(callback);
  return () => {
    subscribers[eventName] = subscribers[eventName].filter((cb) => cb !== callback);
  };
}

export function publish(eventName, data) {
  (subscribers[eventName] ?? []).forEach((cb) => cb(data));
}

Note that subscribe returns an unsubscribe function. Components call it in disconnectedCallback, which stops a replaced section from leaving a dead listener behind. If you skip this, every refresh of the cart drawer adds another callback and each cart change runs the old ones too (a classic leak).

flowchart LR
  A["cart-form<br/>adds an item"] -->|"publish cart:updated"| B(("event bus"))
  B --> C["cart-count"]
  B --> D["cart-drawer"]
  B --> E["shipping-bar"]

One publisher, three subscribers; none of them knows about the others.

The theme editor's section events

In the theme editor, merchants add, remove, move and edit sections without a page reload. The editor refreshes the HTML of the changed section and tells your page about it by dispatching events on the section element. They bubble up to document, and event.detail contains the sectionId (and blockId for block events):

Event When
shopify:section:load a section was added or re-rendered
shopify:section:unload a section is about to be removed or replaced
shopify:section:select / deselect the merchant clicked the section in the sidebar or deselected it
shopify:section:reorder the section order changed
shopify:block:select / deselect a block was selected or deselected

If your component is a custom element, you rarely need section:load, because connectedCallback already runs when the new HTML is inserted. You do need the select events for sliders and tabs: when the merchant selects a slide block in the sidebar, the preview should jump to it.

JavaScript
// Show the selected slide in the editor (read-only example)
document.addEventListener('shopify:block:select', (event) => {
  const block = event.target;
  if (!block.matches('[data-slide]')) return;
  block.closest('slide-show')?.goTo(block);
});

These events fire only in the editor, so ordinary visitors never run this code. For how merchants use that editor, see The Theme Editor and How Merchants Use Your Theme. Elements inside a section carry {{ block.shopify_attributes }} so the editor knows which block they belong to.

Stand-in: custom element lifecycle with an event bus

You cannot construct Shopify's editor here, so this stand-in imitates the two things that matter: a tiny element registry that calls connectedCallback and disconnectedCallback when "HTML" is inserted and replaced, and the event bus above. Watch what happens when the cart drawer is replaced twice, once leaking (no cleanup) and once cleaning up.

JS Stand-in: lifecycle, replacement and the event bus

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In the first run, the removed v1 drawer still redraws, which is the memory and logic leak that disconnectedCallback prevents. In the second run, only v2 reacts. Real custom elements and the real browser do the calling for you; the logic you write is the same.

Live example: a real custom element

This preview uses a real custom element in your browser. The <quantity-input> enhances a plain number field with buttons, announces its value in a live region, and dispatches a bubbling change event that a listener outside the element can hear.

A real custom element: quantity-input

Click the buttons: the number never drops below 1, and the log shows one change event per click. Delete the <script> and the number input would still work by typing, which is the point of progressive enhancement.

Habits that keep theme JavaScript healthy

  • Prefer events over globals. A global window.updateCart() is a promise nobody can keep; an event is a contract anyone can listen to.
  • Scope selectors to this. Inside a component use this.querySelector, not document.querySelector, so two instances do not fight.
  • Clean up. Remove listeners and observers in disconnectedCallback, especially anything attached to document or window.
  • Do not assume order. Another script may define an element after the HTML is parsed. Custom elements upgrade whenever they are defined, so this is mostly handled for you.
  • Ship less. Check the weight of each script against the benefit; app scripts add up (see Theme App Extensions and Third-Party Scripts).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why do custom elements handle a refreshed section without extra code?

    When new HTML containing the tag is inserted, the browser creates the elements and calls connectedCallback, so each new instance initializes itself.
  2. 2. Why wrap customElements.define in a check with customElements.get?

    A script may be loaded twice. A second define call with the same name throws, so the guard avoids breaking the page.
  3. 3. A component subscribes to a bus event. Where should it unsubscribe?

    When the element is removed (for example when a section is replaced), the listener must be removed too, or old callbacks keep running.
  4. 4. Which event tells your page that the merchant selected a block in the theme editor sidebar?

    shopify:block:select (and its deselect twin) fires on the block element so a slider or tab component can reveal the chosen item.
  5. 5. Which loading choice avoids blocking HTML parsing and keeps script order?

    Deferred scripts download in parallel and run in order after the document is parsed. Module scripts behave the same way by default.

Summary

  • Build theme components as custom elements: set up in connectedCallback, clean up in disconnectedCallback, and guard customElements.define.
  • Because new elements initialize themselves, replaced sections and Ajax-rendered HTML need no manual re-initialization.
  • Use a small publish and subscribe bus (or DOM CustomEvents) for communication, and always unsubscribe on removal.
  • Load scripts from assets/ with defer or type="module", and avoid libraries the platform already replaces.
  • Use shopify:section:* and shopify:block:* events only for editor behavior, such as showing the selected slide.

Next, style those components in CSS for Themes: Variables, Layout and Responsiveness.