Search code examples
web-component

Is there a limit to how many web components / custom elements you can define?


I am building a ~largish app with about ~50 components (class definitions and window.customElements.define calls). Do I need to be concerned on how many I define? Can having too much slow down the browsers Dom parsing? Is there a limit to how many I can define?


Solution

  • You won't hit limits with general DOM recommendations:

    Going extreme

    Here is 5000 Custom Elements, all nested:

    let startTime = new Date() / 1;
    let fragment = new DocumentFragment();
    let nested = fragment;
    let name, nr = 5000;
    let done = `${nr} elements done in `;
    do {
      name = "e-" + nr;
      customElements.define(name, class extends HTMLElement {
        connectedCallback() {
          this.append(this.nodeName);
        }
      });
      nested = nested.appendChild(document.createElement(name));
    } while (--nr);
    document.body.append(done, new Date() / 1 - startTime, " milliseconds  ", fragment)


    Comparing speed is a bit senseless ... my Chrome with 30+ extensions is slower than my Edge without any extensions.

    Do think about (CSS) Selectors and Custom Elements

    I did 52 SVG playing cards(in 16 Kb) with Autonomous elements:

    <two-of-hearts></two-of-hearts>
    <ten-of-hearts></ten-of-hearts>
    <ace-of-hearts></ace-of-hearts>
    ...
    <ace-of-spades></ace-of-spades>
    

    Yeah! great Semantic HTML..

    But you can NOT do partial nodeName (CSS) selectors

    So in the end a single Autonomous Element:

    <playing-card is="ace-of-hearts"></playing-card>

    made more sense, to be able to use CSS:

     [is*="hearts"]{
      border : 2px solid green;
     }
    

    and JavaScript:

      let aces = document.querySelectorAll('[is*="ace"]');