Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 39 ยท Tooling and Patterns

Lazy Loading and Distributing Components

Load custom elements on demand with customElements.whenDefined, :defined, upgrades and dynamic import, avoid layout shift, and package components for npm and CDNs.

A page can contain dozens of custom element tags while only a few of them are needed right away. A chart below the fold, a map, a rich-text editor: shipping all their code up front slows the first paint. Web components are well suited to lazy loading, because the browser already knows what to do with a tag whose class is not registered yet: it keeps it as an inert, unknown element, and upgrades it the moment customElements.define() runs.

This lesson shows how that upgrade works, how to avoid layout jumps while waiting, and how to package components so others can use them.

The upgrade process

flowchart LR
  A["Parser sees &lt;x-map&gt;"] --> B["Unknown element<br/>(not :defined)"]
  B -- "define('x-map', Class)" --> C["Upgrade:<br/>constructor runs, callbacks fire"]
  C --> D["Defined element<br/>(:defined)"]

Existing tags are upgraded in place; their attributes and children are kept.

Useful tools:

  • customElements.get("x-map") returns the class, or undefined if not defined.
  • customElements.whenDefined("x-map") returns a promise that resolves when the definition happens (immediately if it already has).
  • customElements.upgrade(root) forces upgrading of elements inside a tree that was created in a way that skipped it.
  • The :defined pseudo-class matches elements whose definition exists (and all built-in elements).
Defining an element late and watching the upgrade

Before the click, the tag is an empty grey placeholder (it matches :not(:defined)). After the click, the same node is upgraded: the constructor and connectedCallback run, the attribute format="short" is still there, and the CSS flips to the :defined look.

Avoiding layout shift

A not-yet-defined component often occupies no space, then pops in and pushes content around. Prevent that:

  • Give the tag reserved dimensions while undefined: x-chart:not(:defined) { display: block; aspect-ratio: 16 / 9; }.
  • Or hide it with visibility: hidden (keeps space) until defined, then show it.
  • Provide meaningful fallback content inside the tag, so users see something sensible even before upgrade or if JavaScript fails. Content in the light DOM is rendered by the browser as normal.

Do not use display: none for the undefined state if the component is above the fold: it removes the element from layout, which causes a shift when it appears. Reserve its space instead.

Properties set before definition

Remember the trap from Attributes vs Properties: a script may assign el.items = [...] before the class exists. That creates an own data property that shadows your accessor. Fix it once, in a base class or helper, by re-applying own properties on upgrade:

Re-applying properties set before upgrade

Without the re-apply loop the early array would be ignored and the list would stay empty. Several libraries do this for you; raw components must do it themselves.

Loading on demand

Typical strategies, from simplest to most refined:

  1. Separate module per component, loaded with a <script type="module"> only on pages that use it.
  2. Dynamic import() when the tag appears or becomes visible (read-only pattern):
JavaScript
const lazy = new IntersectionObserver((entries, obs) => {
  for (const entry of entries) {
    if (entry.isIntersecting) {
      import("./x-chart.js");   // the module calls customElements.define
      obs.unobserve(entry.target);
    }
  }
});
document.querySelectorAll("x-chart").forEach((el) => lazy.observe(el));
  1. A loader map: scan the page for unknown tags (:not(:defined) with a hyphen) and import the matching file by name.
  2. Prefer idempotent definitions: guard with if (!customElements.get("x-chart")) customElements.define(...), because defining the same name twice throws.

Packaging and distribution

Think about the consumer's experience:

  • Consider optional registration. Many libraries export the class and offer a define() helper, so apps can choose the tag name and avoid collisions (two versions of a library cannot both own x-button).
  • Ship ES modules ("type": "module" and an exports map), with the class as the default or named export, plus a side-effect entry (my-lib/x-button.js) that registers it.
  • Publish types (.d.ts) and a Custom Elements Manifest (custom-elements.json), a standard JSON description of your tags, attributes, events, slots, parts and CSS variables. Editors and documentation tools read it.
  • Offer a CDN-friendly build: a single module a page can load with <script type="module" src="...">.
  • Version carefully: attributes, events, slots, parts and CSS variables are your public API; renaming any is a breaking change.
  • Avoid global side effects beyond customElements.define and document them.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens to <x-map> tags already in the page when customElements.define('x-map', ...) runs?

    Existing elements with that name are upgraded: the constructor and callbacks run on the same nodes.
  2. 2. What does customElements.whenDefined(name) return?

    It is a promise, resolving right away if the element is already defined.
  3. 3. Which CSS prevents layout shift for an undefined component?

    Reserving space for the undefined state keeps surrounding content from jumping when the upgrade happens.
  4. 4. Why guard define() with customElements.get(name)?

    A name can only be registered once, so shared or duplicated modules should check first.

Summary

  • Undefined custom tags are inert until define() upgrades them in place.
  • whenDefined, get, upgrade and :defined help you coordinate and style the transition.
  • Reserve space and provide fallback content to avoid layout shift.
  • Re-apply properties set before upgrade; load code on demand with dynamic import().
  • Package as ES modules with types and a Custom Elements Manifest, and keep the public API stable.

Next: Declarative Shadow DOM and Server Rendering