completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

Loading definitions on demand

Learn how to lazy load web components: import each custom element's file only when its tag appears, catch tags added later, and never load a definition twice.

By the end, you can
  • 01
    Load a component only when its tag appearsFind undefined tags with :not(:defined), import each one's file, and catch new tags with a MutationObserver.
  • 02
    Load each definition onceKeep each import's promise, check the registry before define(), and explain why a second copy throws.
  • 03
    Handle order, failures, and costMake a component wait for the tags it uses, stop asking for a missing file, and preload the files a page needs.

How do you lazy load web components?

Asha is checking the menu page for Leaf and Kettle. It shows one price, so it uses one tag from the tea kit: <tea-price>. But the page loads tea-kit/index.js. That file imports every component in the kit, as lesson 1.4 set it up. So the browser downloads all four component files to show one price.

The kit will keep growing. Should every page download every component? Or could a page load only the files for the tags it really has, and load more when new tags appear?

To lazy load web components, find the custom tags on the page that aren't defined yet. Import each one's file with import() the first time its tag appears. Then watch the page with a MutationObserver, so tags added later get their files too.

A tool that does this is called an autoloader. Lesson 2.1 used Web Awesome's autoloader from the outside. This lesson builds one for the tea kit, from the inside. Here is the finished one at work. The page has one kit tag, and it loads the kit's new file, tea-kit/autoload.js:

A page that loads only the kit file it needsPop out in the code editor (opens in a new tab)HTML
<p>Green tea. <tea-price amount="4"></tea-price></p> <script type="module">  import "./tea-kit/autoload.js";   await customElements.whenDefined("tea-price");  for (const name of ["tea-badge", "tea-label", "tea-price", "tea-timer"]) {    console.log(name, customElements.get(name) ? "loaded" : "not loaded");  }</script>
ResultLoading…
  • Line 1 is a paragraph with one <tea-price>.
  • Line 4 loads tea-kit/autoload.js. It's the only kit file the page names.
  • Line 6 waits until tea-price is defined. customElements.whenDefined() gives back a promise, as lesson 4.1 showed.
  • Lines 7 to 9 ask the registry about each of the kit's four tags. Each kit file defines its own tag when it runs. So a defined tag means its file has loaded.

The result shows Green tea. Price: 4. The console prints tea-price loaded, and not loaded for the other three. In Chrome, the page asks for two kit files: autoload.js and tea-price.js. The other three are never downloaded.

Loading one definition on demand. A page holds one tag, tea-price. An arrow goes to autoload.js, which finds the tag, and an arrow marked import() goes to the tea-kit folder. In the folder, only tea-price.js is loaded. tea-badge.js, tea-label.js, and tea-timer.js are crossed out: nothing on the page needs them.page<tea-price>finds the tagautoload.jsimport()tea-badge.jstea-label.jstea-price.jstea-timer.jstea-kit
The autoloader finds the one tag on the page and imports its file. The kit's other three files never load, because no tag needs them.
Real-life analogyA kitchen that orders only what today's dishes need

A small café doesn't keep every ingredient for every dish on its menu. Each morning, the cook reads the orders. A table wants mint tea, so she calls the supplier for mint. Nobody ordered lemon cake, so no lemons arrive. When a new table orders later, she calls again.

In real life: The orders on the kitchen board
In JavaScript: The tags on the page
In real life: Reading the orders
In JavaScript: Finding the tags that aren't defined yet
In real life: Calling the supplier for mint
In JavaScript: import() of tea-kit/tea-price.js
In real life: No lemons arrive
In JavaScript: tea-label.js and the rest never load
In real life: A table that orders later
In JavaScript: A tag added after the page loads
The main idea

Load a component's file the first time its tag appears. An autoloader finds the tags that aren't defined yet, imports one file per tag, and keeps watching for new tags. Each file defines its tag, and the browser upgrades every waiting element.

The rest of the lesson builds the autoloader, piece by piece. First, loading one file. Then finding the tags, and watching for new ones. Then the hard parts: order, loading twice, failures, and cost.

How do you load a custom element's file with dynamic import?

Start with one tag and one file. A static import at the top of a module always loads its file. import() is different. It loads a module when your code reaches it, and gives back a promise. The Dynamic import lesson shows how it works. MDN's import() page shows a common use: load code when the user asks for it. Here, a click asks for a price:

Import the price's file on the first clickPop out in the code editor (opens in a new tab)HTML
<p>Green tea.</p><button>Show the price</button> <script type="module">  const button = document.querySelector("button");  button.addEventListener("click", async () => {    const price = document.createElement("tea-price");    price.setAttribute("amount", "4");    document.querySelector("p").append(" ", price);    await import("./tea-kit/tea-price.js");    console.log("tea-price is defined:", Boolean(customElements.get("tea-price")));  }, { once: true });</script>
ResultLoading…
  • Lines 1 and 2 are a paragraph and a button.
  • Line 6 runs a function when you click. { once: true } on line 12 removes it after the first click.
  • Lines 7 to 9 make a <tea-price> and add it to the paragraph. Nothing defines it yet, so it waits.
  • Line 10 imports the kit's tea-price.js. Its last line defines tea-price, and the waiting price upgrades.
  • Line 11 prints tea-price is defined: true.

Click Show the price in the result. Price: 4 appears after Green tea.. Before the click, Chrome downloads no kit file at all. After it, it downloads tea-price.js, and only that. Why it matters: code for a part of the page that a visitor never opens costs that visitor nothing.

One file per tag

An autoloader can't have one import() line for every tag. It needs a rule that turns a tag's name into a file's address. The tea kit already has one, from lesson 1.4: each file is named after its tag. So tea-price lives in tea-kit/tea-price.js.

Build the file's address from the tag's namePop out in the code editor (opens in a new tab)HTML
<p>Green tea. <tea-price amount="4"></tea-price></p> <script type="module">  function load(name) {    return import(`./tea-kit/${name}.js`);  }   const first = await load("tea-price");  const second = await load("tea-price");  console.log("Same module:", first === second);  console.log("It exports:", Object.keys(first).join(", "));</script>
ResultLoading…
  • Line 4 is a function, load(), that takes a tag's name.
  • Line 5 builds the address from the name, with a template literal. For tea-price, that's ./tea-kit/tea-price.js.
  • Lines 8 and 9 load tea-price twice. Line 10 prints Same module: true.
  • Line 11 prints It exports: TeaPrice, the class the file exports.

The second call didn't load the file again. The browser keeps each module it loads, by its address. Ask for the same address again, and you get the same module. In Chrome, this page asks for tea-price.js once, so its define() runs once. Why it matters: a load() can't run a file twice by accident. A failed download is different, as you'll see later.

How do you find custom elements that aren't defined yet?

Next, the autoloader needs a list of tags to load. It wants only custom tags whose class isn't defined yet. Lesson 2.4 styled them with the :defined selector. :not(:defined) matches the opposite: the elements still waiting. querySelectorAll() finds every element that matches:

Find every tag that is still waitingPop out in the code editor (opens in a new tab)HTML
<tea-label name="Green tea" minutes="3"></tea-label><tea-price amount="4"></tea-price><wa-badge>New</wa-badge><p>Fresh this week.</p> <script type="module">  const waiting = document.querySelectorAll(":not(:defined)");  const names = [...waiting].map((element) => element.localName);  console.log("Not defined:", names.join(", "));  const ours = names.filter((name) => name.startsWith("tea-"));  console.log("Ours:", ours.join(", "));</script>
ResultLoading…
  • Lines 1 to 3 are three custom tags. Nothing on this page defines them.
  • Line 4 is a paragraph, a built-in element.
  • Line 7 finds every element that matches :not(:defined).
  • Line 8 turns them into a list of names. localName is an element's tag name, in lowercase.
  • Line 9 prints Not defined: tea-label, tea-price, wa-badge.
  • Line 10 keeps the names that start with tea-. Line 11 prints Ours: tea-label, tea-price.

The <p> isn't listed. Built-in elements always match :defined. So does a name with no hyphen, like <foo>, because it can never be a custom element.

Why line 10 matters: a page can hold tags from other libraries, like this Web Awesome badge. The tea kit has no file for wa-badge. So the kit's autoloader loads only names with the kit's prefix, tea-. Lesson 3.1 showed why a kit's names share a prefix. Web Awesome's own autoloader does the same with wa-.

Tags inside shadow roots

There's one place this search never looks. Lesson 2.1 found that Web Awesome's autoloader can't see inside shadow roots. Here is why:

A search of the document stops at a shadow rootPop out in the code editor (opens in a new tab)HTML
<shop-menu></shop-menu> <script type="module">  const menu = document.querySelector("shop-menu");  menu.attachShadow({ mode: "open" });  menu.shadowRoot.innerHTML = `<tea-price amount="4"></tea-price>`;   const inPage = document.querySelectorAll(":not(:defined)");  const inMenu = menu.shadowRoot.querySelectorAll(":not(:defined)");  console.log("In the page:", [...inPage].map((el) => el.localName).join(", "));  console.log("In the shadow root:", [...inMenu].map((el) => el.localName).join(", "));</script>
ResultLoading…
  • Line 1 is a menu. Nothing defines shop-menu here.
  • Line 5 gives the menu a shadow root: a private tree of its own. Line 6 puts a <tea-price> inside it.
  • Line 8 searches the document. Line 9 searches the shadow root.
  • Line 10 prints In the page: shop-menu. Line 11 prints In the shadow root: tea-price.

The document search found the menu, but not the price in its shadow root. A shadow root is a separate tree, and searches of the document stop at its edge. Lesson 4.1 showed that define() does reach into shadow roots. Your own searches don't.

Two separate trees. On the left, the page holds shop-menu. Under it, document.querySelectorAll() finds shop-menu. An arrow marked attachShadow() goes from the menu to its shadow root on the right, which holds tea-price. Under the shadow root, menu.shadowRoot.querySelectorAll() finds tea-price.page<shop-menu>attachShadow()<tea-price>shadow rootdocument.querySelectorAll()finds shop-menumenu.shadowRoot.querySelectorAll()finds tea-price
The menu's shadow root is a tree of its own. A search of the document stops at the menu. Only a search that starts from the shadow root finds the price inside it.
Real-life analogyA stocktake of the shop floor

Once a month, Ravi counts everything on the shop floor. He walks every aisle and checks every shelf. The tasting room has its own door, and he doesn't go in. If it needs counting, its own staff count it and hand him the list.

In real life: The shop floor
In JavaScript: The page's own tree
In real life: Walking every aisle
In JavaScript: document.querySelectorAll()
In real life: The tasting room behind its own door
In JavaScript: A component's shadow root
In real life: The tasting room's staff counting it
In JavaScript: The component handing its shadow root to the autoloader

So who searches a shadow root? Only code that can reach it. The component that made it can hand it to the autoloader. The kit's autoloader takes any root to search: the document, or a shadow root. You'll see a component do that in the practical section.

How do you catch custom elements added later?

Pages change after they load. A click opens a cart, or a script adds a list of teas. The autoloader needs to hear about new elements. A MutationObserver is a browser object that calls your function after the page changes. The Observers lesson covers it. Two of its options matter here:

  • childList: true reports children that are added or removed.
  • subtree: true reports changes anywhere inside, not only right under the element you watch.
What the observer reports when a box is addedPop out in the code editor (opens in a new tab)HTML
<main></main> <script type="module">  const observer = new MutationObserver((records) => {    for (const record of records) {      for (const node of record.addedNodes) {        console.log("Added:", node.localName);      }    }  });  observer.observe(document.body, { childList: true, subtree: true });   const box = document.createElement("div");  box.innerHTML = `<tea-price amount="4"></tea-price>`;  document.querySelector("main").append(box);</script>
ResultLoading…
  • Line 4 makes an observer. Its function gets a list of records, one for each change.
  • Lines 5 and 6 go through each record, and each node it added. A node is anything in the page's tree, like an element or some text.
  • Line 7 prints the node's tag name.
  • Line 11 starts watching the body, with both options. MDN's observe() page lists them all.
  • Lines 13 and 14 make a box with a price inside. Line 15 adds the box to the page.

It prints one line: Added: div. The price isn't reported on its own. One append() added one node, the box, and the price came inside it. Why it matters: an autoloader that checks only addedNodes misses every tag that arrives inside something else.

Real-life analogyA delivery log that lists boxes

The tea shop keeps a log of deliveries. Each line says something like "one box, 10:05". It doesn't list what's inside. To know if the box holds mint tea, someone has to open it.

In real life: A line in the delivery log
In JavaScript: One record
In real life: The box it names
In JavaScript: A node in addedNodes
In real life: Opening the box to look inside
In JavaScript: Searching the node with querySelectorAll()

So the autoloader checks two things for each element that's added: the element itself, and every element inside it. Here is the kit's autoloader doing that. The button adds a box with a label inside:

The kit's autoloader catches a label added laterPop out in the code editor (opens in a new tab)HTML
<button>Add a label</button><main></main> <script type="module">  import "./tea-kit/autoload.js";   document.querySelector("button").addEventListener("click", () => {    const box = document.createElement("div");    box.innerHTML = `<tea-label name="Mint tea" minutes="4"></tea-label>`;    document.querySelector("main").append(box);  });</script>
ResultLoading…
  • Line 5 loads the autoloader. The page has no kit tags yet, so nothing else loads.
  • Lines 8 and 9 make a box with a <tea-label> inside. Line 10 adds it to the page.

Click Add a label. Mint tea: brew for 4 minutes appears. The observer reported the box, the autoloader searched inside it, and it imported tea-label.js. In Chrome, that file is asked for only after the click. Click again, and the new label works at once with no new download. tea-label is defined now, so a new label starts out upgraded.

What if one component needs another to load first?

With lazy loading, files arrive in any order. Whichever file downloads first runs first. Usually that's fine: when a file runs, its define() upgrades every waiting element with that name. But some components use other components. Here is a cart from Leaf and Kettle's own page. It adds up the amount of each kit price inside it. That's the property lesson 4.2 gave the price.

Playground: change which file arrives first
A cart that adds up the prices inside itPop out in the code editor (opens in a new tab)HTML
<shop-cart>  <tea-price amount="4"></tea-price>  <tea-price amount="5"></tea-price></shop-cart> <script type="module">  await import("./tea-kit/tea-price.js");  await import("./shop-cart.js");</script>
ResultLoading…
Try it yourself
The prices are ready when the cart reads them.

Line 7 loads tea-price.js, so both prices upgrade. Line 8 loads the cart. Its connectedCallback() reads amount from two real prices, and prints Total: 9.

The page always has the same cart and two prices. Lines 7 and 8 change places, and so does the shop-cart.js tab. Each run starts in a fresh page.
  • Lines 1 to 4 are the cart, with two prices inside.
  • Lines 7 and 8 load the two files. The buttons change their order.
  • Open the shop-cart.js tab. Line 2 is connectedCallback(). It runs as soon as the cart's class is defined, because the cart is already on the page.
  • Lines 3 and 4 find the prices and add up their amounts. Number() turns each amount into a number.

With tea-price.js first, the console prints Total: 9. With shop-cart.js first, it prints Total: NaN. The prices were still waiting, and a waiting element has no amount property. So price.amount is undefined, and Number(undefined) is NaN, which means "not a number". The prices show up a moment later, but the total is already wrong.

Two orders of arrival. Top row: tea-price.js arrives first, so tea-price is defined, then shop-cart connects and prints Total: 9. Bottom row: shop-cart.js arrives first, so shop-cart connects while each price's amount is undefined, and it prints Total: NaN.tea-price.js arrives firsttea-price definedshop-cart connectsTotal: 9the right totalshop-cart.js arrives firstshop-cart connectsamount: undefinedTotal: NaNread too early
The cart reads the prices the moment it connects. If tea-price.js came first, it reads two real amounts. If the cart came first, it reads two waiting elements.

Lesson 4.1 showed that one define() upgrades elements in page order, parents before children. That's in the HTML Standard's steps for define(). But lazy loading calls define() once per file, in the order the files arrive. Nothing promises which file comes first.

Real-life analogyA recipe card that lists what it needs

Asha bakes scones from a recipe card. The card lists what she needs at the top: flour, butter, and milk. She gets them all out before she starts. If she started mixing before the milk arrived, the dough would come out wrong.

In real life: The recipe card
In JavaScript: shop-cart.js
In real life: The list at the top of the card
In JavaScript: import "./tea-kit/tea-price.js" on line 1
In real life: Mixing before the milk arrives
In JavaScript: Reading amount before tea-price is defined
In real life: Waiting for the milk
In JavaScript: await customElements.whenDefined("tea-price")

There are two fixes. Try both buttons:

  • The cart imports tea-price.js. Line 1 of shop-cart.js becomes import "./tea-kit/tea-price.js";. A module's imports run before the module itself, so tea-price is always defined first. Lesson 2.1 gave the same advice: a component imports the tags it uses.
  • The cart waits with whenDefined(). Line 3 waits for tea-price before it reads anything. Now the order the files arrive in doesn't matter at all.

Both print Total: 9. Why it matters: when a component reads another component's properties, or calls its methods, it must make sure that component is defined. Import it, or wait for it. Then the order of arrival can't break it.

How do you avoid defining a custom element twice?

A registry holds each name once. Lesson 3.1 showed that a second define() with a taken name throws a NotSupportedError. MDN lists it under define()'s exceptions. So when could lazy loading define a tag twice?

Not by loading the same file twice. You saw that with load(): one address, one module, one define(). The danger is the same code at two addresses. Say another team's gift card widget brings its own copy of tea-price.js, in a vendor folder:

The same file twice, then a copy from another addressPop out in the code editor (opens in a new tab)HTML
<p>Green tea. <tea-price amount="4"></tea-price></p> <script type="module">  await import("./tea-kit/tea-price.js");  await import("./tea-kit/tea-price.js");  console.log("The same address twice: no error");   try {    await import("./vendor/tea-price.js");  } catch (error) {    console.log(`${error.name}: ${error.message}`);  }</script>
ResultLoading…
  • Lines 4 and 5 import the kit's tea-price.js twice. Line 6 prints The same address twice: no error.
  • Line 9 imports the copy in vendor/. Its code is the same, but its address isn't. So the browser treats it as a new module and runs it.
  • The copy's last line calls define() for tea-price again. That throws, so line 9's import() rejects, and line 11 prints the error.

Line 11 prints NotSupportedError: Failed to execute 'define' on 'CustomElementRegistry': the name "tea-price" has already been used with this registry. With lazy loading, this message usually means that two copies of a component reached the page.

Real-life analogyAn order book by the kitchen phone

In a busy kitchen, two cooks might both notice the mint is low. If both call the supplier, two boxes arrive. So the kitchen keeps an order book by the phone. Before calling, a cook checks the book. If mint is written down, she waits for that delivery. If a full box is already on the shelf, nobody orders at all.

In real life: The order book
In JavaScript: The autoloader's loading Map
In real life: Checking the book before calling
In JavaScript: loading.has(name)
In real life: Writing an order down
In JavaScript: loading.set(name, …)
In real life: A full box already on the shelf
In JavaScript: customElements.get(name) gives a class

The kit's autoloader checks two things before it imports a file:

  • Line 5 of autoload.js asks the registry first. customElements.get() gives the class for a name, or undefined. If some other file already defined the tag, the kit doesn't load its own copy.
  • Line 6 checks the loading Map. A Map is a list of keys and their values. The autoloader keeps one entry per tag name: the promise from its import(). If the name is there, the file is already on its way.

A component file can guard itself the same way. Check get() before you call define():

Check the registry before define()Pop out in the code editor (opens in a new tab)JavaScript
class TeaPrice extends HTMLElement {}
class OldTeaPrice extends HTMLElement {}

function defineOnce(name, constructor) {
  if (customElements.get(name)) {
    console.log(`<${name}> is already defined. Skipped.`);
    return;
  }
  customElements.define(name, constructor);
}

defineOnce("tea-price", TeaPrice);
defineOnce("tea-price", OldTeaPrice);
console.log("TeaPrice won:", customElements.get("tea-price") === TeaPrice);
  • Lines 1 and 2 are two classes that both want tea-price.
  • Line 5 asks the registry if the name is taken. If it is, line 6 prints a note, and line 7 stops.
  • Line 12 defines tea-price with TeaPrice. Line 13 is skipped, so it prints <tea-price> is already defined. Skipped..
  • Line 14 prints TeaPrice won: true.

The first class wins, and the second one is never used. That's fine when both copies are the same version. When they differ, the page quietly runs the first one. Shoelace, the library that became Web Awesome, checked get() first too. It said nothing when the versions matched, and printed a warning when they didn't. The real fix for two versions on one page is a scoped registry: a second registry for part of the page. Lesson 1.2 introduced them, and stage 3 teaches them.

What happens when a component's file fails to load?

Files fail. The network drops, a deploy leaves a file out, or a page uses a tea- tag the kit doesn't have. When the download fails, import() rejects with a TypeError (MDN). In Chrome, its message starts with Failed to fetch dynamically imported module, then the file's address.

Then comes a surprise. The browser keeps every module that loaded, but not one that failed. The HTML Standard's steps for fetching a module remove a failed download from the browser's list. So the next import() of that address asks the server again. An autoloader with no memory would ask again every time the page changes. Try it with tea-cup, a tag the kit has no file for:

Playground: ask for a missing file three times
Three calls to load() for a tag with no filePop out in the code editor (opens in a new tab)HTML
<script type="module">  function load(name) {    console.log("Asking for", name);    return import(`./tea-kit/${name}.js`).catch((error) => {      console.warn(`Couldn't load <${name}>: ${error.name}`);    });  }   for (let cup = 1; cup <= 3; cup++) await load("tea-cup");</script>
ResultLoading…
Try it yourself
It asks for the missing file three times.

Each call to load() runs import() again. A failed download isn't kept, so the browser asks the server again every time, and every time it fails.

The kit has no tea-cup.js, so every try fails. Watch how many times the console says Asking for tea-cup.

With A load() with no Map, the console prints Asking for tea-cup three times, with three warnings. In Chrome, the page asks the server for tea-cup.js three times. With A load() that keeps each promise in a Map, it asks once and warns once. Line 5 checks the Map, line 7 stores the first promise, and line 11 hands that promise to every later call.

It's like phoning a shop that has closed. One call tells you. Calling every five minutes only wastes your time and theirs.

The kit's autoloader works the same way. Its .catch() prints one warning, like Couldn't load <tea-cup> from /tea-kit/tea-cup.js. The promise stays in the Map, so the kit never asks again on that page. The tag stays waiting. Style waiting tags, as lesson 2.4 showed, so a missing component doesn't leave a blank hole. And whenDefined("tea-cup") would wait forever, so race it against a timer, as lesson 2.4 did.

Why it matters: one missing file should cost one request and one warning, not a request on every change to the page.

Is lazy loading faster than one bundle?

Not always. Lazy loading saves bytes: a page downloads only the components it uses. But each file is its own request, and some requests must wait for others:

  • The autoloader itself has to arrive and run before it can ask for anything.
  • A component that imports another adds one more step. The Web Components Community Group calls this risk a "loading pyramid": A loads, which loads B and C, which load D and E.

Picture it with one price, where each kit file takes 200 ms to arrive:

Two timelines, each file taking 200 milliseconds. Without a hint, autoload.js downloads from 0 to 200 ms, and tea-price.js only starts after it, from 200 to 400 ms. With modulepreload, autoload.js and tea-price.js both download from 0 to 200 ms.Without a hintautoload.jstea-price.jsWith modulepreloadautoload.jstea-price.js0 ms200 ms400 ms
Each kit file takes 200 ms here. Without a hint, the browser learns about tea-price.js only after autoload.js has run. With modulepreload, both download at once.

Without a hint, the browser learns about tea-price.js only after autoload.js has run. So the price is ready after about 400 ms. A modulepreload link tells the browser about a module early. Put <link rel="modulepreload" href="/tea-kit/tea-price.js"> in the page's head. The browser downloads the module and gets it ready, but doesn't run it. When the autoloader imports it, it's ready. In Chrome, both files then download together, and tea-price.js is asked for once.

So add the hint for tags you know a page needs, like the price on every menu page. Don't preload everything: MDN warns that preloading too much can slow down other work on the page. The Resource hints lesson goes deeper on preloading. ES modules in the browser shows when one bundle still wins. A page that uses most of the kit may do better with index.js, or one bundled file.

Until its file arrives, a lazy tag can't do anything. GitHub's Catalyst library can lazy load its components. Its guide suggests keeping each one small enough to load within 100 ms on a "Fast 3G" connection.

Loading even later

An autoloader loads a component as soon as its tag appears. Some loaders wait longer. Catalyst's lazyDefine() can wait until the tag is near the screen, or until the first click or key press. Zach Leatherman's is-land waits for conditions like "visible" or "idle". Stage 13 comes back to loading components fast.

Why doesn't the browser do this for you?

People have asked for it. A proposal called lazy custom element definitions would add customElements.defineLazy(name, loader). You'd give a name and a function that loads its file. The browser would call that function when the tag first appears. The Web Components Community Group's 2022 report lists it as a "strawperson" proposal: an early sketch, with open questions and some disagreement. No browser offers it to web pages. So for now, an autoloader is a few dozen lines of your own JavaScript.

Adding the autoloader to the tea kit

Now put the pieces together. This lesson's version of the kit adds one file, tea-kit/autoload.js. The four components stay as they were. A page loads either index.js, for the whole kit at once, or autoload.js, for only what it uses. Here is the new file:

tea-kit/autoload.js, the kit's autoloaderJavaScript
const folder = new URL("/tea-kit/", document.baseURI);
const loading = new Map();

export function load(name) {
  if (customElements.get(name)) return Promise.resolve();
  if (!loading.has(name)) {
    const url = new URL(`${name}.js`, folder);
    const done = import(url).catch(() => {
      console.warn(`Couldn't load <${name}> from ${url.pathname}`);
    });
    loading.set(name, done);
  }
  return loading.get(name);
}

export function discover(root) {
  const found = [...root.querySelectorAll(":not(:defined)")];
  if (root instanceof Element && root.matches(":not(:defined)")) found.push(root);
  for (const element of found) {
    if (element.localName.startsWith("tea-")) load(element.localName);
  }
}

export function watch(root) {
  discover(root);
  new MutationObserver((records) => {
    for (const record of records) {
      for (const node of record.addedNodes) {
        if (node instanceof Element) discover(node);
      }
    }
  }).observe(root, { childList: true, subtree: true });
}

watch(document);
  • Line 1 works out the kit's folder. /tea-kit/ is its path from the root of the site. document.baseURI is the page's address. new URL() joins them into a full address, like https://leafandkettle.example/tea-kit/. So the page decides where the kit lives. Web Awesome also finds its folder from the page, through its base path.
  • Line 2 is the loading Map.
  • Lines 4 to 14 are load(). Lines 5 and 6 are the two checks from before. Line 7 builds the file's address. Line 8 imports it, and lines 8 to 10 turn a failure into one warning. Line 11 stores the promise, and line 13 returns it.
  • Lines 16 to 22 are discover(). Line 17 finds the waiting elements inside root. Line 18 adds root itself, when it's a waiting element. Lines 19 to 21 load each one whose name starts with tea-.
  • Lines 24 to 33 are watch(). Line 25 searches root once. Lines 26 to 32 then watch it, and run discover() on every element that's added.
  • Line 35 starts watching the whole document as soon as the file runs.

export on lines 4, 16, and 24 lets other files use the three functions. A page can call load("tea-timer") to load a tag before it appears. And a component can hand its shadow root to watch(). Here is a menu from Leaf and Kettle's own page doing that. Its name starts with shop-, not tea-, so the kit's autoloader leaves it alone:

A menu hands its shadow root to the kit's autoloaderPop out in the code editor (opens in a new tab)HTML
<tea-label name="Mint tea" minutes="4"></tea-label><shop-menu></shop-menu> <script type="module">  import "./tea-kit/autoload.js";  import "./shop-menu.js";</script>
ResultLoading…
  • In index.html, line 1 is a kit label. Line 2 is the page's own menu.
  • Line 5 loads the kit's autoloader. Line 6 loads the menu's file.
  • Open the shop-menu.js tab. Line 6 gives the menu a shadow root. Line 7 puts a kit price inside it.
  • Line 8 hands the shadow root to the kit's watch(). The autoloader searches it, and keeps watching it.

The result shows Mint tea: brew for 4 minutes, then the menu with Green tea Price: 4. In Chrome, the page downloads autoload.js, shop-menu.js, tea-label.js, and tea-price.js. It never downloads tea-badge.js or tea-timer.js. Delete line 8 of shop-menu.js, and the menu shows Green tea with no price. Exercise 6 is about this.

Why it matters: the kit now has two ways in. index.js loads everything at once. autoload.js loads only what a page uses, when it uses it.

Common mix-ups

Read each row from left to right: what goes wrong, what you see, and what fixes it.

What can go wrong when components load on demand
What goes wrong?What do you see?What fixes it?
A kit tag sits inside a component's shadow root.The autoloader never finds it, so the tag stays blank.The component calls watch(this.shadowRoot), or imports the file itself.
A tag arrives inside a box that was added.The record's addedNodes lists only the box.Search the added node and every element inside it.
A component reads another tag before that tag is defined.It reads undefined, and the cart prints Total: NaN.Import the file it uses, or wait with whenDefined().
Two copies of one component load from two addresses.The second define() throws a NotSupportedError.Load one copy, or check customElements.get() before define().
A file is missing, or the network fails.import() rejects with a TypeError, and each new import() asks the server again.Keep the promise in a Map, warn once, and leave the tag waiting.
  • "import() downloads a file again every time you call it." No. A module that loaded is kept by its address. Every later import() of that address gets the same module. Only a failed download is tried again.
  • "document.querySelectorAll() finds every tag on the page." No. It stops at shadow roots. A component has to search its own shadow root, or hand it to the autoloader.
  • "A MutationObserver reports every element that was added." No. addedNodes lists the nodes that were put in, not the elements inside them. Search inside each one.
  • "Loading the same component twice is always harmless." No. The same address twice is harmless. A copy at a second address runs its define() again, and that throws a NotSupportedError.
  • "Files load in the order the tags appear on the page." No. They run in the order they arrive. A component that needs another one imports it, or waits with whenDefined().
  • "Lazy loading always makes a page faster." No. Each file is a request, and some must wait for others. Preload the files a page always needs, and bundle when a page uses most of the kit.

Practice exercises

Answer first, then use the hints. Each result runs live, so you can check yourself.

Exercise 1 · Warm-upWhich files load?

This page loads the kit's autoloader. Which kit files does it import?

<tea-label name="Oolong" minutes="5"></tea-label><tea-timer seconds="3"></tea-timer> <script type="module">  import "./tea-kit/autoload.js";</script>
ResultLoading…

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · Warm-upWhat did the observer see?

    What does line 6 print?

    <ul></ul> <script type="module">  new MutationObserver((records) => {    const added = [...records[0].addedNodes].map((node) => node.localName);    console.log(records.length, "record:", added.join(", "));  }).observe(document.body, { childList: true, subtree: true });   document.querySelector("ul").innerHTML =    `<li><tea-price amount="4"></tea-price></li><li><tea-price amount="5"></tea-price></li>`;</script>
    ResultLoading…

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeLook inside the box

      Click Add a label. The label stays blank, because this small autoloader never loads its file. Fix lines 8 to 10. What does the result show after one click?

      <button>Add a label</button><main></main> <script type="module">  new MutationObserver((records) => {    for (const record of records) {      for (const node of record.addedNodes) {        if (node instanceof Element && node.matches(":not(:defined)")) {          import(`./tea-kit/${node.localName}.js`);        }      }    }  }).observe(document.body, { childList: true, subtree: true });   document.querySelector("button").addEventListener("click", () => {    const box = document.createElement("div");    box.innerHTML = `<tea-label name="Mint tea" minutes="4"></tea-label>`;    document.querySelector("main").append(box);  });</script>
      ResultLoading…

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · PracticeGuard the second copy

        The page loads the kit's price and the copy in vendor/, and the copy throws. Change the last line of the vendor/tea-price.js tab so it doesn't. What does the page print then?

        <p>Green tea. <tea-price amount="4"></tea-price></p> <script type="module">  await import("./tea-kit/tea-price.js");  try {    await import("./vendor/tea-price.js");    console.log("Both copies loaded");  } catch (error) {    console.log(error.name);  }</script>
        ResultLoading…

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeMake the cart wait

          Here shop-cart.js arrives first, and the cart prints Total: NaN. Change only the shop-cart.js tab. What does the cart print once it works?

          <shop-cart>  <tea-price amount="4"></tea-price>  <tea-price amount="5"></tea-price></shop-cart> <script type="module">  await import("./shop-cart.js");  await import("./tea-kit/tea-price.js");</script>
          ResultLoading…

          Answer, then press Check. Spacing and letter case don’t matter.

            Exercise 6 · ChallengeLoad the menu's price

            The menu in this page shows Green tea, but no price. Fix the shop-menu.js tab. What does the menu show then?

            <tea-label name="Mint tea" minutes="4"></tea-label><shop-menu></shop-menu> <script type="module">  import "./tea-kit/autoload.js";  import "./shop-menu.js";</script>
            ResultLoading…

            Answer, then press Check. Spacing and letter case don’t matter.

              Check your understanding

              For each question, ask what the browser knows at that moment: which tags it has seen, and which files have arrived.

              The loading on demand quiz · 7 questionsScore: first tries count
              1. Question 1 of 7What does line 9 of this page print?

                Read the code, then predictPop out in the code editor (opens in a new tab)HTML
                <tea-label name="Green tea" minutes="3"></tea-label>
                <tea-price amount="4"></tea-price>
                <wa-badge>New</wa-badge>
                <p>Fresh this week.</p>
                
                <script type="module">
                  const waiting = document.querySelectorAll(":not(:defined)");
                  const names = [...waiting].map((element) => element.localName);
                  console.log("Not defined:", names.join(", "));
                  const ours = names.filter((name) => name.startsWith("tea-"));
                  console.log("Ours:", ours.join(", "));
                </script>

                Choose an answer to see the explanation.

              2. Question 2 of 7This page adds a box with a price inside it. What does the observer print?

                Read the code, then predictPop out in the code editor (opens in a new tab)HTML
                <main></main>
                
                <script type="module">
                  const observer = new MutationObserver((records) => {
                    for (const record of records) {
                      for (const node of record.addedNodes) {
                        console.log("Added:", node.localName);
                      }
                    }
                  });
                  observer.observe(document.body, { childList: true, subtree: true });
                
                  const box = document.createElement("div");
                  box.innerHTML = `<tea-price amount="4"></tea-price>`;
                  document.querySelector("main").append(box);
                </script>

                Choose an answer to see the explanation.

              3. Question 3 of 7A page calls import("./tea-kit/tea-price.js") a second time. What happens?

                Choose an answer to see the explanation.

              4. Question 4 of 7Why does the kit's load() keep each import's promise in a Map?

                Choose an answer to see the explanation.

              5. Question 5 of 7What does the cart print when shop-cart.js arrives before tea-price.js?

                Read the code, then predictPop out in the code editor (opens in a new tab)HTML
                <shop-cart>
                  <tea-price amount="4"></tea-price>
                  <tea-price amount="5"></tea-price>
                </shop-cart>
                
                <script type="module">
                  await import("./shop-cart.js");
                  await import("./tea-kit/tea-price.js");
                </script>

                Choose an answer to see the explanation.

              6. Question 6 of 7A second copy of tea-price.js, at another address, runs its define(). What happens?

                Choose an answer to see the explanation.

              7. Question 7 of 7What does <link rel="modulepreload" href="/tea-kit/tea-price.js"> change on a page that uses the autoloader?

                Choose an answer to see the explanation.

              Key takeaways

              • To lazy load web components, import each component's file the first time its tag appears on the page.
              • :not(:defined) finds the custom elements still waiting. Keep only your prefix, so other libraries' tags are left alone.
              • Searches of the document stop at shadow roots. A component hands its own shadow root to the autoloader.
              • A MutationObserver with childList and subtree reports added nodes. Search each one, and everything inside it.
              • Files arrive in any order. A component imports the tags it uses, or waits for them with whenDefined().
              • One address loads once. A copy at a second address throws a NotSupportedError, so check get() before define().
              • The browser tries a failed file again on the next import(). Keep each promise in a Map, and warn once.
              • Each lazy file is a request. Preload the files a page always needs.

              Remember the one-liner.
              An autoloader finds the tags that aren't defined yet, imports each one's file once, and keeps watching for new ones.

              Sources

              The facts on this page come from these standards, docs, and source files:

              Coming next: Attributes and properties. Attributes are strings in HTML, and properties are values in JavaScript. Learn which to offer, and how to keep them in sync.

              CompleteFrontend Clear concepts. Working examples.