Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 39 ยท Custom Elements

Upgrading Elements and whenDefined

Understand how undefined custom elements are upgraded, how to wait with customElements.whenDefined, how to prevent flashes of unstyled content, and lazy-load components.

HTML is parsed from top to bottom, but your component's JavaScript may load later, or never. What does the browser do with a <user-card> tag that appears before customElements.define has run? It treats it as an undefined element: a plain, inline element with no behavior. When the definition finally arrives, the browser upgrades every matching element already in the page. Understanding this process lets you load components lazily, avoid layout jumps and write code that does not break depending on script order.

Undefined, then upgraded

The following example puts markup first, runs a delayed definition, and prints what the element is at each stage.

Watching an upgrade

For the first 600 ms the note is plain text. Then the definition runs, the constructor is called on the existing element (the browser does not create a new one), connectedCallback follows, and the note gains its style.

Upgrade order

When define runs, the browser finds every matching element in the document and, in tree order, runs the constructor, then attributeChangedCallback for each observed attribute, then connectedCallback. Because the element already has attributes and children at this moment, the constructor restrictions that apply to createElement do not matter for upgraded elements; code must still follow them because the same class is used both ways.

customElements.whenDefined

How do you run code that needs a component to be ready? Not with setTimeout. The registry provides a promise:

JavaScript
await customElements.whenDefined("fancy-note");
document.querySelector("fancy-note").doSomething();

whenDefined(name) resolves with the constructor once the name is defined (immediately if it already is). It rejects with a SyntaxError if the name is invalid.

Waiting for a definition

The await pauses until define runs; then the method call is safe. This is the pattern for code in one file that depends on a component from another.

Preventing the flash of undefined content

Until the definition loads, the browser shows the raw light DOM text and your layout reflows when the component renders. The :defined pseudo-class gives a CSS-only fix:

CSS
/* Reserve space and hide the raw content until upgraded */
user-card:not(:defined) {
  display: block;
  min-height: 4rem;
  visibility: hidden;
}

For components that should degrade gracefully (for instance, one that enhances a link list), you might do the opposite and show the plain content until upgrade, styling it to look acceptable. Decide per component: hide when the undefined state is meaningless, show when it is readable HTML.

Lazy loading components

Combine :defined with dynamic import to load a heavy component only when it is needed.

JavaScript
const observer = new IntersectionObserver((entries) => {
  for (const entry of entries) {
    if (entry.isIntersecting) {
      import("./chart-widget.js");   // defines <chart-widget>
      observer.disconnect();
    }
  }
});
observer.observe(document.querySelector("chart-widget"));

When the module runs customElements.define("chart-widget", ...), the browser upgrades the waiting tag. (This snippet is read-only because the sandboxed preview has no second file to import.) The page never needs to know when the upgrade happens, so there is no coupling.

Forcing an upgrade: customElements.upgrade

Elements created with innerHTML inside an inert context, such as a template's content or an element created with DOMParser, are not upgraded until they are inserted into the document. When you need an element upgraded while it is detached, call:

JavaScript
customElements.upgrade(someRoot);

It upgrades every defined custom element in the subtree, even though it is not connected to the document.

Properties set before definition

If your page sets a property on a not-yet-defined element, the value becomes an own data property that hides your class accessor. Re-assign in the constructor, as shown in the properties lesson:

JavaScript
constructor() {
  super();
  for (const name of ["items", "open"]) {
    if (Object.hasOwn(this, name)) {
      const value = this[name];
      delete this[name];
      this[name] = value;
    }
  }
}

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the browser do with a custom tag whose class is not defined yet?

    The element stays in the DOM as a generic element and is upgraded when define runs.
  2. 2. What does customElements.whenDefined('x-a') return?

    It returns a promise, so you can await the definition.
  3. 3. Which CSS selects elements that have NOT been upgraded yet?

    :defined matches built-ins and upgraded custom elements, so :not(:defined) matches the waiting ones.
  4. 4. When an existing element is upgraded, which constructor behavior happens?

    Upgrades call the constructor for the element that is already in the DOM.

Summary

  • Elements written before their definition are undefined, then upgraded in place when define runs.
  • The upgrade order is constructor, attribute callbacks, then connectedCallback.
  • Use customElements.whenDefined to wait for a component instead of timers.
  • :not(:defined) styles the loading state and prevents layout jumps.
  • Lazy-load heavy components with dynamic import(), and use customElements.upgrade for detached trees.

Next: Shadow DOM Basics