Skip to content
Advertisement

How would I import a custom web component asynchronously?

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:

JavaScript

The Element’s Class Declaration:

JavaScript

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

JavaScript

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:

JavaScript

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

Advertisement

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:

JavaScript

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.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement