liveBook · Manning

HTMLImports.whenReady

As explained in Web Components in Action

A callback API provided by the HTML Imports polyfill that runs after imported HTML resources are ready.

HTMLImports.whenReady is a callback API from the HTML Imports polyfill. It runs after imported resources are fully ready, allowing a Web Component to query its imported template, clone it, and append the clone. section 7.1

Populate an imported component

Inside connectedCallback(), pass a function to HTMLImports.whenReady. Query the template from the import's owner document, clone template.content with cloneNode(true), and append the clone to the component. section 7.1

Listing 7.3. Populating Web Component markup from an HTML Import template
class SampleComponent extends HTMLElement {                    #1
   connectedCallback() {
       HTMLImports.whenReady( () => {
           const template =                                    #2
               ownerDoc.querySelector('template');
           const clone =                                       #3
               template.content.cloneNode(true);
           this.appendChild(clone);                            #4
       });
   }
}

const ownerDoc =                                               #5
       HTMLImports.importForElement(document.currentScript);
if (!customElements.get('sample-component')) {
    customElements.define('sample-component', SampleComponent);
}

Inspect the complete callback flow, including owner-document lookup, template cloning, component definition, and insertion. section 7.1

How Web Components in Action covers it

How deep it goes
Explains callback timing and its role in querying, cloning, and appending a template, but not polyfill internals.
Examples
Uses a sample component whose imported template is cloned and appended during connectedCallback.
What it assumes
Assumes familiarity with HTML Imports, Web Components, templates, DOM cloning, and connectedCallback.
What you can do after
Build an HTML Imports-based Web Component that populates itself after imported resources become ready.
How it connects
Links HTML Imports with Web Components, owner documents, templates, custom elements, and connectedCallback.

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.