Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML <template> Element versus Javascript Template Literals

Mozilla says Web components consist of three main technologies:

  1. Custom elements
  2. Shadow DOM
  3. HTML templates

Is number 3, "HTML templates", even necessary in light of ECMAscript's Template Literals?

Look at this example I got from James Milner:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Web Component</title>
    <script type="text/javascript">
    // We define an ES6 class that extends HTMLElement
    class CounterElement extends HTMLElement{
            constructor() {
                    super();
                    // Initialise the counter value
                    this.counter = 0;

                    // We attach an open shadow root to the custom element
                    const shadowRoot= this.attachShadow({mode: 'open'});

                    // We define some inline styles using a template string
                    const styles=`
                            :host {
                                    position: relative;
                                    font-family: sans-serif;
                            }

                            #counter-increment, #counter-decrement {
                                    width: 60px;
                                    height: 30px;
                                    margin: 20px;
                                    background: none;
                                    border: 1px solid black;
                            }

                            #counter-value {
                                    font-weight: bold;
                            }
                    `;

                    // We provide the shadow root with some HTML
                    shadowRoot.innerHTML = `
                            <style>${styles}</style>
                            <h3>Counter</h3>
                            <slot name='counter-content'>Button</slot>
                            <button id='counter-increment'> - </button>
                            <span id='counter-value'> 0 </span>
                            <button id='counter-decrement'> + </button>
                    `;

                    // We can query the shadow root for internal elements
                    // in this case the button
                    this.incrementButton = this.shadowRoot.querySelector('#counter-increment');
                    this.decrementButton = this.shadowRoot.querySelector('#counter-decrement');
                    this.counterValue = this.shadowRoot.querySelector('#counter-value');

                    // We can bind an event which references one of the class methods
                    this.incrementButton.addEventListener("click", this.decrement.bind(this));
                    this.decrementButton.addEventListener("click", this.increment.bind(this));

            }
            increment() {
                    this.counter++
                    this.invalidate();
            }
            decrement() {
                    this.counter--
                    this.invalidate();
            }
            // Call when the counter changes value
            invalidate() {
                    this.counterValue.innerHTML = this.counter;
            }
    }
    // This is where the actual element is defined for use in the DOM
    customElements.define('counter-element', CounterElement);
    </script>
</head>
<body>
    <counter-element></counter-element>
</body>
</html>

Notice how he doesn't use an HTML template, but instead uses an ecmascript template literal to set the innerHTML of the shadowRoot.

After this, he uses querySelector to get internal elements of the shadowRoot and he ultimately adds event listeners to the increment and decrement buttons.

If you were to use a HTML template, instead of an ecmascript template literal, what does this gain you?

Conceptually, I'm struggling to find a situation where I'd prefer an HTML Template Element over an Ecmascript Template Literal.

Please advise.

like image 585
Lonnie Best Avatar asked Nov 15 '18 02:11

Lonnie Best


People also ask

Can you use template literals in HTML?

Template literals are great for HTML because you can add newlines and very cleanly have dynamic classes and other attributes.

What is JavaScript template literal?

Template literals are literals delimited with backtick ( ` ) characters, allowing for multi-line strings, string interpolation with embedded expressions, and special constructs called tagged templates.

What is HTML template element?

The <template> HTML element is a mechanism for holding HTML that is not to be rendered immediately when a page is loaded but may be instantiated subsequently during runtime using JavaScript. Think of a template as a content fragment that is being stored for subsequent use in the document.

Why would you need to use a template literal in JavaScript?

Template literals provide an easy way to interpolate variables and expressions into strings. The method is called string interpolation.


Video Answer


1 Answers

The template tag is not 'required' for Web Components per se. It probably made more sense when HTML Imports were being pushed, allowing for importing and reusing HTML snippets, but that has since ceased. Here you could have imported a template and reused that.

It's important to note the specifications are designed to be standalone and can be used interdependently of each other also, which makes them versatile. The HTML tag has use cases outside of the realm of Web Components; it's useful because it allows you to define a piece of markup that doesn't render until instantiated via JavaScript later on. Indeed you can use templates without using any of the other specifications (Custom Elements, Shadow DOM etc).

The template tag can certainly be used in conjunction with the other specs. For example, we could have used it in the example shown to arguably make the code less imperative and more markup focused like so:

 <template id="counterTemplate">
   <style>
         :host {
             position: relative;
             font-family: sans-serif;
         }

         #counter-increment, #counter-decrement {
             width: 60px;
             height: 30px;
             margin: 20px;
             background: none;
             border: 1px solid black;
          }

         #counter-value {
             font-weight: bold;
         }
   </style>
   <h3>Counter</h3>
   <slot name='counter-content'>Button</slot>
   <button id='counter-increment'> - </button>
   <span id='counter-value'> 0 </span>
   <button id='counter-decrement'> + </button>
</template>

And then use this later in JavaScript like so:

   const template = document.querySelector('#counterTemplate');
   const counter = document.cloneNode(template);
   shadowRoot.appendChild(counter);

The downside here is that it would require that the template existed in the DOM prior to the instantiation as it is relying on the #counterTemplate template being there. In some ways this makes the Custom Element less portable, hence why template literal might be more desirable. I haven't tested the performance of both, but my gut tells me that the template would possibly be more performant.

Disclaimer: I wrote the original blog post

like image 89
James Milner Avatar answered Oct 20 '22 00:10

James Milner