W3cubDocs

/DOM

CustomElementRegistry.whenDefined

The whenDefined() method of the CustomElementRegistry interface returns a Promise that resolves when the named element is defined.

This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

Syntax

customElements.whenDefined(name).then(function() {
  // Do something related to the element
});

await customElements.whenDefined(name);

Parameters

name
Custom element name.

Return value

A Promise that resolves to undefined when the custom element is defined. If the custom element is already defined, the promise is resolved immediately.

Examples

This example uses whenDefined() to detect when the custom elements that make up a menu are defined. The menu displays placeholder content until the actual menu content is ready to display.

<nav id="menu-container">
  <div class="menu-placeholder">Loading...</div>
  <nav-menu>
    <menu-item>Item 1</menu-item>
    <menu-item>Item 2</menu-item>
     ...
    <menu-item>Item N</menu-item>
  </nav-menu>
</nav>
const container = document.getElementById('menu-container');
const placeholder = container.querySelector('.menu-placeholder');
// Fetch all the children of menu that are not yet defined.
const undefinedElements = container.querySelectorAll(':not(:defined)');

const promises = [...undefinedElements].map(
  button => customElements.whenDefined(button.localName)
);

// Wait for all the children to be upgraded, 
// then remove the placeholder.
await Promise.all(promises);
container.removeChild(placeholder);

Browser compatibility

Feature Firefox (Gecko) Chrome Internet Explorer Opera Safari
Basic support No support 54 No support 41 10.1
Feature Firefox Mobile (Gecko) Chrome for Android IE Mobile Opera Mobile Safari Mobile
Basic support No support 54 No support 41 10.1

© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/CustomElementRegistry/whenDefined