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
Because this technology's specification has not stabilized, check the compatibility table for usage in various browsers. Also note that the syntax and behavior of an experimental technology is subject to change in future versions of browsers as the specification changes.

Syntax

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

Parameters

name
Custom element name.

Return value

A Promise that resolves 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>
  let container = document.getElementById('menu-container');
  let placeholder = container.querySelector('.menu-placeholder');
  // Fetch all the children of menu that are not defined yet.
  let undefinedElements = container.querySelectorAll(':not(:defined)');

  let promises = [...undefinedElements].map(button => {
    return customElements.whenDefined(button.localName);
  });

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

Browser compatibility

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

© 2005–2017 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