Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 38 ยท Custom Elements

Upgrading and Defining Elements

See how the browser upgrades unknown tags when you call customElements.define, how to wait with whenDefined, avoid layout flashes with :defined, and extend built-in elements.

HTML pages are parsed from top to bottom, but JavaScript modules often load later. So a page can contain <my-card> long before the class for it exists. What does the browser do with the tag in the meantime? It treats it as a harmless unknown element, and when customElements.define("my-card", ...) runs, it upgrades every matching element already in the page. This lesson explains that process and the tools around it.

Understanding upgrades helps you avoid flashes of unstyled content, race conditions between components, and mysterious errors such as "element.method is not a function".

Upgrade in action

The element in the next example exists in the document before its class is defined. Press the button to define it later and watch what changes.

Define later, upgrade now

Before the call, shout is undefined, because the tag is a plain HTMLElement. After define, the same object has the class's prototype, and its constructor and connectedCallback run. Nothing was removed or recreated; the existing node was upgraded in place.

sequenceDiagram
  participant P as HTML parser
  participant D as Document
  participant R as customElements registry
  P->>D: finds late-greeter tag
  Note over D: plain HTMLElement, not defined
  R->>R: define("late-greeter", Class)
  R->>D: upgrade all matching elements
  D->>D: constructor, attributeChangedCallback, connectedCallback

Upgrade: elements are found first, the class arrives later.

Waiting for a definition: whenDefined

Code that calls methods on a custom element must be sure it is ready. customElements.whenDefined(name) returns a promise that resolves when the name is registered, and after the upgrade of existing elements has been queued.

JavaScript
await customElements.whenDefined("late-greeter");
document.querySelector("late-greeter").shout();

This is the right way to coordinate when your page script and the component module load in an unknown order. For Lit components that also have asynchronous rendering, wait for the element's updateComplete promise as well (covered in The Lit Update Lifecycle).

You can also upgrade explicitly, with customElements.upgrade(root), which upgrades custom elements inside a subtree that was created without being connected. It is rarely needed.

Avoiding the flash: the :defined selector

Until the class arrives, <my-card> shows its raw children, usually text in the wrong layout. When the upgrade happens, the page jumps. The :defined pseudo-class matches elements that are built-in or registered, so you can hide the others:

CSS
my-card:not(:defined) {
  visibility: hidden;   /* keeps layout space */
}

Prefer visibility: hidden over display: none when you want the page not to jump when the component appears. You can also reserve a minimum height, or show a skeleton placeholder with the same size. Lit components that render asynchronously still show a short empty period after definition, so some sites also hide the element until a ready attribute is set.

Hiding undefined elements

The reserved min-height keeps the paragraph in place when the note appears, so nothing moves.

Upgrade order and children

When many elements are upgraded at once, the browser processes them in document order. A parent's constructor runs before its children's. At that time the children might not be defined yet, so a parent should not call methods on children inside connectedCallback without waiting:

JavaScript
async connectedCallback() {
  await customElements.whenDefined("tab-item");
  this.querySelectorAll("tab-item").forEach((tab) => tab.setup());
}

An even better design avoids the dependency: let children announce themselves with an event (see Events in Lit) or let the parent read data from slots.

Reading properties set before the upgrade

There is one more catch. Code may set a property on the element before it is upgraded:

JavaScript
card.items = [1, 2, 3]; // card is still a plain HTMLElement

This creates an ordinary own property on the object. When the class later arrives, its getter and setter on the prototype are shadowed by that own property, and your setter never runs. The solution is to "upgrade the property": in the constructor or connectedCallback, check whether the instance already has an own value, delete it, and re-assign it through the setter:

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

Lit does this for you for every declared reactive property, which is one of the quiet benefits of using it.

Customized built-in elements

Besides autonomous custom elements (your own tags), the standard has customized built-ins: classes that extend a real element such as HTMLButtonElement and are used with the is attribute.

JavaScript
class FancyButton extends HTMLButtonElement { /* ... */ }
customElements.define("fancy-button", FancyButton, { extends: "button" });
HTML
<button is="fancy-button">Save</button>

They keep built-in behavior, such as form submission and keyboard handling, for free. However, Safari does not support them and has said it will not, and they cannot have shadow roots on every base element. For this reason most libraries, including Lit, use autonomous elements and wrap a real <button> in the shadow tree when they need button behavior. Form-Associated Elements with Lit shows the modern alternative for form controls.

Common mistakes

  • Calling a method right after adding a script tag, before define ran. Use whenDefined.
  • Hiding components with display: none and then seeing the page jump when they appear.
  • Setting a property before upgrade and losing it (the property upgrade pattern fixes this).
  • Relying on customized built-ins when Safari users matter.
  • Defining the element in a module that is loaded defer or async and then expecting synchronous access.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens to a custom tag in the HTML before its class is registered?

    The browser keeps the node. When customElements.define runs, existing matching elements are upgraded in place.
  2. 2. Which API gives you a promise for when a tag name is registered?

    whenDefined returns a promise that resolves once the name has been defined.
  3. 3. What does the :defined pseudo-class match?

    Undefined custom elements do not match :defined, so you can style or hide them until the upgrade happens.
  4. 4. Why does a property set before upgrade need special handling?

    An own property hides the prototype setter. Delete it and re-assign it through the setter after upgrade.
  5. 5. Which browser does not support customized built-in elements (is=)?

    Safari has chosen not to implement them, which is why most libraries use autonomous elements.

Summary

  • Elements in the page when define runs are upgraded in place; the constructor and callbacks then run.
  • customElements.whenDefined(name) waits for registration; customElements.get(name) checks it.
  • Use :not(:defined) with visibility: hidden and a reserved size to avoid layout jumps.
  • Properties set before upgrade must be re-applied through the setter; Lit does this automatically.
  • Customized built-ins exist but lack Safari support, so prefer autonomous elements.

Next: Shadow DOM Basics