How would I import a custom web component asynchronously?

Tags: , , ,



I have made my custom input element (modern text input for forms) into a web component. The .js file that I made to implement it has three parts.

The HTML Template:

const textInputTemplate = document.createElement('text-input-template');
textInputTemplate.innerHTML =
`
<div class="text-input-container">
    <!--Irrelevant-->
</div>
`;

The Element’s Class Declaration:

class textInput extends HTMLElement {

    static get observedAttributes() {
        return ['readonly'];
    }

    constructor () {
        super();
        // Shadow root
    } // End of constructor()

    connectedCallback () {
        // Custom attributes
    } // End of connectedCallback()

    disconnectedCallback () {
        // Remove event listeners
    } // End of disconnectedCallback()

    attributeChangedCallback(attribute, oldValue, newValue) {
        // Updatable attributes: readonly
    } // End of attributeChangedCallback()   
}

Lastly, The Method That Associates the Custom Element to a Tag Name:

window.customElements.define('text-input', textInput);

Question: I am worried that using <script src="./module-name"> is inefficient or could cause errors down the road because it loads synchronously after the rest of the page has loaded. Therefore, I’m wondering if there is a cleaner/more professional method to importing the web component asynchronously without sticking the whole module into a function like this:

export function textInput { // insert entire modules contents here }

Because I need all three parts of the module for the web component to work, I can’t only export the web component class.

Answer

I know this is an old question but is not resolved and I’ve faced the same issue, and is as simple as include async when load the script in this way:

<script src="./module-name" async>

You can check here or here

Where say, for example:

When present, it specifies that the script will be executed asynchronously as soon as it is available.

If the async attribute is present, then the classic script will be fetched in parallel to parsing and evaluated as soon as it is available.

So you don’t have to worry about lock rest of the page since every scrpit will be loaded in parallel as soon as possible.



Source: stackoverflow