Home > Back-end >  How to use HTML templates with javascript Web component
How to use HTML templates with javascript Web component

Time:12-08

HTML templates are nice and fast. The problem is HTML import has been deprecated. This means it makes the most sense to put web components each in their own .js file instead of .html files. However if one uses a .js file, then as far as I can tell, one can't use a precompiled template to attach at the shadow DOM, one has to use some fixed string that I imagine is parsed every time.

With .html web component one could do:

    shadowRoot.appendChild(myTemplate.content.cloneNode(true));

However in a .js file you have to do something like:

something.innerHTML = `
  <style>
   
    ...
    /* lots of style */
  </style>
  <b>I'm in shadow dom!</b>
  <!-- lots of html -->
  <slot></slot>
`;

Is this not a bad idea because the text must be revaulated every time, whereas a template is evaulated once?

So what is the recommened way of embedding one's style and html in a .js file for a web component?

I am using vanilla JS, no frameworks.

CodePudding user response:

1 for Vanilla code, your code will last another 26 JavaScript years.

There is no recommended way, it all depends on your use case.

  • You can put <template id="MY-COMPONENT">in your main HTML file,
    and do document.getElementById("MY-COMPONENT").content.cloneNode(true) in your component code (knowing when your DOM is ready)

  • You can do document.createElement("template"), and take it from there

  • You can use the <load-file> Web Component to load external HTML files.
    (no template advantage here)

So it all comes down to understanding what your application needs.

Note that the pattern you see in many blogs:

 let template = document.createElement("template");
 template.innerHTML = ` CSS & HTML CONTENT `;

 ...

 this.shadowRoot.appendChild(template..content.cloneNode(true));

In many use cases, where a parsed template is hardly re- used, is an expensive way of writing:

  this.shadowRoot.innerHTML = ` CSS & HTML CONTENT `;

Be aware the append template approach has (potential) (edge-case) disadvantages as well;
its content is parsed async, while .innerHTML= is synchronous.

An while you are at it, be sure to learn the differences:

  • Related