skip to Main Content

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


  1. You can find custom elements, hide them, load classes async and upgrade elements:

    class CustomElement extends HTMLElement{
      connectedCallback() {
        const template = document.createElement("template")
        template.innerHTML = /* html */ `
          <style>
            :host {
              background-color: yellow;
            }
          </style>
    
          <slot></slot>
        `
        const shadowRoot = this.attachShadow({ mode: "open" })
        shadowRoot.appendChild(template.content.cloneNode(true))
      }
    }
    // you can also traverse DOM tree, could be faster
    document.querySelectorAll('*').forEach(async el => {
      if(el.tagName.includes('-')){
    
        let display;
        [{display}, el.style.display] = [el.style, 'none'];
    
        const name = el.tagName.toLowerCase().replace(/^w|-w/gd, m => m.at(-1).toUpperCase());
    
        // use something like import() to load a custom element class
        const factory = await new Promise(r => setTimeout(() => r(eval(name)), 200));
    
        customElements.define(el.tagName.toLowerCase(), factory);
        customElements.upgrade(el);
    
        el.style.display = display;
      }
    });
    <custom-element>Custom Element</custom-element>
    Login or Signup to reply.
  2. 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:

    class ElementA extends HTMLElement {
      constructor() {
        super();
        // Initialize the custom element
      }
    
      // Define custom methods and properties
    }
    
    if (!customElements.get('element-a')) {
      customElements.define('element-a', ElementA);
    }
    

    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:

    <!DOCTYPE html>
    <html>
      <head>
        <title>Custom Elements Example</title>
        <script async src="element-a.js"></script>
        <!-- Include other JavaScript modules here -->
      </head>
      <body>
        <!-- Use the custom element here -->
        <element-a></element-a>
      </body>
    </html>
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search