liveBook · Manning

customElements.whenDefined

As explained in Web Components in Action

customElements.whenDefined is a browser API method that returns a promise fulfilled when a specified custom element name has been defined.

customElements.whenDefined returns a promise that fulfills when a named custom element has been defined. It lets code wait for one specific Web Component instead of treating all components as ready together. section 14.2

Wait for a delayed component definition

A component is defined after a two-second delay. customElements.whenDefined('sample-component').then(...) runs once that definition exists, while the page can already contain <sample-component>. section 14.2

Listing 14.2. Using a promise to detect when a specific component is defined
<html>
<head>
   <title>Custom Elements When Defined</title>
   <script>
       class SampleComponent                               #1
               extends HTMLElement {
           constructor() {
               super();
               this.attachShadow({mode: 'open'});
               this.shadowRoot.innerHTML = 'my component';
           }
       }

       setTimeout( function() {                            #2
           if (!customElements.get('sample-component')) {
               customElements.define('sample-component', SampleComponent);
           }
       }, 2000);

   customElements.whenDefined(                             #3
     'sample-component').then( ()=>{
       console.log('defined now!');
   });
   </script>
</head>
<body>
<sample-component></sample-component>
</body>
</html>

Follow the complete example: define SampleComponent after a delay, avoid redefining it with customElements.get, and react through the returned promise. section 14.2

How Web Components in Action covers it

How deep it goes
Explains promise-based readiness and demonstrates delayed definition, but stops short of detailing promise internals.
Examples
Uses SampleComponent, a two-second setTimeout, a custom element instance, and a promise callback.
What it assumes
Assumes basic JavaScript promises and custom-element registration through customElements.define and customElements.get.
What you can do after
Apply it via the Custom Elements API to delay work until a named Web Component has been defined.
How it connects
Connects customElements.whenDefined with Custom Elements API, customElements.define, customElements.get, promises, and Web Components.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Web Components in Action. The section links point to the parts of the book it draws on.