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
