Use of Template with HTML Custom Elements
Asked Answered
V

2

13

I just started learning about the HTML custom elements, and through reading a series of intros, tutorials, and documentation, I think I have a good handle on how it works, but I have a philosophical question on the proper way to use or not use the <template> tag.

Custom elements give you the ability to encapsulate new functionality, simplifying the structure of your HTML document, and allowing you to simply insert a <my-custom-element>...</my-custom-element> tag instead of <div class="my-custom-element"><span class="part1">...</span><span class="part2">...</span></div>.

The class definition for the element then sets up the structure and functionality of that element. A bunch of the tutorials then describe how to use <template>...</template> and <slot>...</slot> to set up the contents of the custom element. You would then have to then include the template code in every HTML document in which you want to use the element rather than setting it up in the custom element class's constructor. Doesn't this run counter to the fact that custom elements help simplify and encapsulate functionality in a way that makes them more portable? Or am I misunderstanding the proper usage and/or placement of the template within the document?

Looking through SO, the closest I can find to addressing this is this question:

How to stamp out template in self contained custom elements with vanilla js?

But the answer essentially sidesteps this all together and says "Don't use <template>," and so doesn't really clear up my confusion.

Voltmer answered 21/9, 2018 at 2:53 Comment(0)
S
11

Actually <template> elements can be imported from another document via HTML Imports, along with the Javascript code that will define the custom element:

<link rel="import" src="my-custom-element.html">
...
<custom-element></custom-element>

So it doesn't need to be included in a every HTML document. This post shows a minimal example.

HTML Imports are implemented only in Chrome and Opera. If you want to use them in the with Firefox and Safari you'll need to use the HTML Imports polyfill.

On the other hand and for the moment, Mozilla and Apple don't intend to implement HTML Imports natively in their respective browsers. Therefore they recommend to define custom elements with pure Javascript modules (with import or <script src="...">), and promote template literals strings instead, which offer some advantages (variables, functions), but are sometimes more complicated to code in an IDE (because of their string representation).

Maybe in the future standard HTML modules will be adopted by all browsers, and <template> will come back in the spotlight...

Note that without HTML Imports you can still import yourself some HTML documents with fetch():

fetch( "template.html" )
    .then( stream => stream.text() )
    .then( text => 
        customElements.define( "c-e", class extends HTMLElement {
            constructor() {
                super()
                this.attachShadow( { mode: 'open'} )
                    .innerHTML = text
            }
        } )
    )

Update 2019

HTML Imports won't be supported natively after Chrome 73. You should then use the other solutions listed above (the polyfill, an alternate module loader, JS import, or a direct download with fetch).

Swift answered 21/9, 2018 at 21:21 Comment(6)
Thanks, I was unaware of HTML imports, sounds like the right solution. But given the lack of support, am I correct in understanding that you are advocating template literal strings instead? If so, I am still left with the question of why not just build the element programatically in the custom element's JS class? It would seem to me that including a large block of HTML as a string in JS is unnecessarily complicating things.Voltmer
HTML Imports were the right solution... until September when Google announced the would deprecate the feature (https://mcmap.net/q/777204/-how-to-package-or-import-html-templates-without-html-imports/4600982). Actually I was advocating HTML Imports (with polyfill) but now... :-( As a developer and a designer I consider using HTML documents for templates is a better practice than template literals but the guys from Google and especially Mozilla and Apple seem to have other interests... Some people are not at the right place: in 2018 there's still no import feature for the 1st plateform in the world. Can you believe that?Swift
Interesting. Thanks for your help! I'm leaning towards building things programmatically, then. It seems more readable to me to colocate building the components of my custom element with the class that implements it than calling on a template literal string located somewhere else in my JS file. But perhaps this is just because I come initially from a C++/Java background, where putting giant amounts of data or content in a big string is frowned upon.Voltmer
@Swift would you define a complete HTML file in "template.html" or just the html elements like button etc ?Heteropterous
@J.Doe just the html contentSwift
@bjg222, I don't think this one has cleared your question. I just got the same puzzle as yours, ie., why they use template in an encapsulated component(custom element). After all, a template is meant to be reused. If it is in a custom element, it's un-reusable. Have you got the answer now?Ounce
A
1

Disclaimer: I'm an author of the rich-component library mentioned below.

After some time of experimenting with custom elements and recently raising a full blown project based solely upon them I'd like to share my insights on this:

  • any component tiny as it is, is a candidate to grow to some beast
  • HTML part of it may grow to a point where it is very non-convenient to keep it within JS
  • do use template, built and parsed once and from that point cloned and injected into the shadow root - this is the same best practice as to use document fragment instead of mutating a living DOM
  • if the template contents should be changed from component's instance to instance - some kind of data binding framework may be used, and if minimalist approach on those is taken - it might still be easier and more performant to deal with a cloned-from-template document fragment than operate on string or template literals

In order to not write the same dozens of lines over and over again I've prepared rich-component library, which:

  • normalizes some API for template provisioning and all those 'clone template, create shadow, inject template's content into it' lines of repeating code
  • known to fetch html contents when html URL is provided
  • caches the templates so the fetch is done only once
Alfilaria answered 25/12, 2019 at 17:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.