Search code examples
javascripthtmldomweb-componentnative-web-component

Vanilla WebComponents approaches: is there any real difference between "importing js from html" and "fetching html from js" file


Context: until now I didn't mind about how import template html file to my vanilla webcomponent because I always wrote small html codes. So I have coded html on top of my webcomponent .js file and do something like:

const template = document.createElement("template");
template.innerHTML = `<div id="firstdiv"><input id="inputAny"/></div>`;

class anyVanillaWebComponent extends HTMLElement {
...
  connectedCallback() {
    this.attachShadow({ mode: "open" });
    this.shadowRoot.appendChild(template.content.cloneNode(true));
    const inputAny = this.shadowRoot.getElementById("inputAny");
...

This is quite common find in tutorials, blogs and foruns. Now I want to separate html from javascript assuming this will make my project tree more clear.

Searching around I found some discussion based on assumption that "import" will not be supported anymore in Browsers [(see UPDATE discussion on bottom about alternatives to import)].1

Basically this drove me to two possibilities:

1 - importing .js file to html from html Exemplifying:

<template id="my-webcomponent-template">
  <link rel="stylesheet" href="./some.css">
   <div>some content ...</div>
</template>
<script src="MyWebcomponent.js"></script>

2 - fetch asynchronously my-webcomponent.html from .js file

(async () => {
  const res = await fetch('/MyWebcomponent.html');
  const textTemplate = await res.text();
  const HTMLTemplate = new DOMParser().parseFromString(textTemplate, 'text/html')
                           .querySelector('template');

  class MyWebcomponent extends HTMLElement {...

Based on such discussion from 2017, it seems I should avoid the option 1 but it is not clear for me why and if there is some real advantage on option 2. So my straight question is: is there any real diference between "importing" and "fetching" html file while coding Vanilla Webcomponents which is expected to be rendered straight by browsers that support natively Webcomponents (for instance, Chrome)?


Solution

  • If you don't plan to use your custom element in various pages then the 2 solutions are good.

    In the first one it could be faster because you will save an HTTP request, for the HTML template is immediately available in the main HTML page.

    But if you plan to reuse the custom element (or for better code separation), the second solution is better because the consumer is separated from the web component.