14

Since Html-Imports are now deprecated in Chrome (https://www.chromestatus.com/feature/5144752345317376) and will be removed, I wonder what the alternatives are.

I'm currently using Html-Imports to import Html-Templates. I see only two alternatives so far:

  • Bundling all HTML-files together in one file. This would also improve donwload times in production, but this would decrease encapsulation and modularization. There is a polymer-bundler that would do the job by traversing the HTML-Import-Statements in separated HTML-Files. But this would mean, that HTML-Imports remain in my Code even if they are not supported by any Browsers in future.
  • Building some kind of module loader using XHttpRequests and knitting the templates into one HTML-File at runtime. This would preserve encapsulation and modularization, but this has a bad smell to me since I would basically rebuild the import-Statements on my own.

Is there a new vanilla way to import Html-Templates? (By "vanilla" I basically mean a way without any additional tools like precompiler or bundler involved)

treeno
  • 2,510
  • 1
  • 20
  • 36
  • 1
    I'm afraid your second solution is the only one availabale by now. (Or with fetch https://stackoverflow.com/q/52435955/4600982) – Supersharp Oct 14 '18 at 00:04
  • 3
    What a pitty. I really hope they will come up with an idiomatic way to package and import WebComponents. Otherwise I can hardly see how this is going to become a coherent design. – treeno Oct 14 '18 at 18:57
  • What a pitty, yes... or otherwise they should be replaced in their job. – Supersharp Oct 16 '18 at 10:32
  • See HTML Modules https://github.com/MicrosoftEdge/MSEdgeExplainers/blob/master/HTMLModules/explainer.md and https://groups.google.com/a/chromium.org/forum/#!msg/blink-dev/ewfRSdqcOd8/w_Fr6rJ3DQAJ and https://github.com/w3c/webcomponents/blob/gh-pages/proposals/html-module-spec-changes.md and background discussion at https://github.com/w3c/webcomponents/issues/645 and some issue discussion at https://github.com/w3c/webcomponents/issues/783 – sideshowbarker Feb 01 '19 at 04:32

2 Answers2

14

The deprecation of HTML Imports has essentially changed the load order of resources. Custom Elements have essentially become script-first rather than Template-first. If your element needs a template, load it from the script. If not, just go to work. Frankly, while I was resistant to it for the first couple of weeks, I have grown to love it. And it turns out that loading external resources such as templates is not so bad.

Here is some simple code that will load an HTML Template from an external file:

using async/await:

    async function getTemplate(filepath) {
        let response = await fetch(filepath);
        let txt = response.text();

        let html =  new DOMParser().parseFromString(txt, 'text/html');
        return html.querySelector('head > template');
    }

Promise-based:

    function getTemplate(filepath) {
        return fetch(filepath)
            .then(response => {
                let txt = response.text();
                let html = new DOMParser().parseFromString(txt, 'text/html');

                return html.querySelector('template');
            });
    }   

Both can be invoked with both of the following:

async/await:

    let tpl = await getTemplate('path/to/template.html');

Promises:

    getTemplate('path/to/template.html')
        .then(function doSomething(tpl) {
            // Put your code here...
        });

The resulting code is simple enough that it can be implemented with very little effort in a variety of ways. In fact, I have a little SuperClass that handles it for me and all of my custom-elements inherit from it. You could use a mixin, instead, which I have also done in the past.

The hard work is just flip-flopping the order, and even that is not very hard unless you are using 1000s of components. It could probably be automated with very little work.

Fuzzical Logic
  • 12,947
  • 2
  • 30
  • 58
  • For clarity: The promise approach is more cross-browser friendly. Although async/await is being implemented across browsers fairly quickly. – Fuzzical Logic Feb 01 '19 at 00:48
  • 1
    Does `template` selector need to exist in advance or it's the code that it is generating it? I am trying to `console.log` the `tpl` variable but I am always getting `null`. Does this work with local paths as well? – umbe1987 Mar 31 '20 at 07:18
  • Can you call getTemplate from the constructor of HTMLElement? What renders while the template is being fetched? – Ron Newcomb Sep 10 '20 at 02:48
  • @RonNewcomb : Yes, you can, but that is not ideal. What renders while it is waiting is essentially a div. Static templates should generally only be loaded once per registration (since they aren't likely to ever change). I typically call it from a static method on the registration of the element. Another alternative is to on-demand load the template and store it statically. This allows the constructor to not have to worry about it. – Fuzzical Logic Nov 28 '20 at 13:25
  • If you're getting `null` on your selectors, try `await response.text()`. It returns a promise! – AlgoRythm May 05 '22 at 01:31
3

index.html:

<script type="module">
  import { CustomHTMLElement } from './CustomHTMLElement.js'

  customElements.define('custom-html-element', CustomHTMLElement)
</script>

<custom-html-element></custom-html-element>

CustomHTMLElement.js:

import { createTemplate } from './createTemplate.js'

const template = createTemplate(`
  <template>
    <style>
      .box {
        width: 2rem;
        height: 2rem;
        background-color: red;
      }  
    </style>
    <div class="box"></div>
  </template>
`)

export class CustomHTMLElement extends HTMLElement {
  constructor() {
    super()
    const templateContent = template.content
    const shadowRoot = this.attachShadow({mode: 'closed'})
    shadowRoot.appendChild(templateContent.cloneNode(true))
  }
}

createTemplate.js:

import { createDOM } from './createDOM.js'

export function createTemplate(templateText) {
  const dom = createDOM(templateText)
  const template = dom.querySelector('template')
  return template
}

createDOM.js:

export function createDOM(htmlText) {
  return new DOMParser().parseFromString(htmlText, 'text/html')
}

See https://github.com/SanjoSolutions/web-components for the code licensed under the Unlicense license.

Sanjo
  • 1,240
  • 9
  • 11