I am curretly adding some customm elements for an inhouse framework , however I noticed that we are getting all the elements on an index file to use them inside the html.
Do you know a better way to do this ? like a lazy instantiation.
current code :
customElements.define('element-a', ElementA);
customElements.define('element-b', ElementB);
customElements.define('element-c', ElementC);
customElements.define('element-d', ElementD);
customElements.define('element-f', ElementF);
....
2
Answers
You can find custom elements, hide them, load classes async and upgrade elements:
Yes, you can use a lazy instantiation approach to create custom elements in HTML on demand. This approach involves defining the custom elements only when they are first used in the HTML.
Here’s an example of how you can implement lazy instantiation for custom elements:
1. Create a JavaScript module for each custom element.
For example, you can create a file called element-a.js with the following content:
2. Include the JavaScript modules in your HTML file using the async
attribute.
For example, you can include the element-a.js module in your HTML file as follows:
By using the async attribute, the JavaScript modules will be loaded asynchronously, which can improve the performance of your HTML file.
3. When the HTML file is loaded, the custom elements will be created on
demand.
When the browser encounters the tag, it will check if the ElementA class has been defined. If it hasn’t been defined yet, the browser will execute the code in the element-a.js module, which will define the ElementA class and register it as a custom element.
By using this approach, you can create custom elements in HTML on demand and avoid loading unnecessary custom elements.
Note: Make sure to test your custom elements thoroughly to ensure that they work correctly with the lazy instantiation approach.