Manngo
Manngo

Reputation: 16301

HTML Template Element: Clarification

I have recently discovered the HTML template element, and would appreciate some clarification.

As far as I can tell, the three distinguishing features are:

Aside from these, a <template> might have been a div, hidden from the screen and the DOM. In this regard, the JavaScript used to take advantage of the template is the same as if trying to fake one using a div.

Is this correct? I ask because it would be relatively easy to fake one for nonsupporting browsers.

Upvotes: 9

Views: 3358

Answers (2)

Supersharp
Supersharp

Reputation: 31181

There are some major differences:

  1. Script (<script>) in a <template> element is not executed immediately.

  2. Media content (<audio>, <video>, <img>) inside the template won't be loaded immediately.

    Instead they will be executed or loaded once they are inserted in the rendered DOM tree.

  3. querySelector() method calls and CSS selectors won't explore the content of a <template>, but you can still access the elements inside by using querySelector() on its content property.

  4. With HTML5 template, you can access all its content in the form of a Document Fragment, and insert it in the DOM tree using appendChild(), instead of modifying innerHTML.

  5. <template> elements can be placed in the <head> element.

  6. You access the template content as a string using .innerHTML or as a DocumentFragment using .content.

It's quite difficult then to fake all thses behaviors. There are some polyfills that can partially do that. I'd recommend Neovov's one.


Look at this illustrative example:

//explore the content of the template
var script = T1.content.querySelector( 'script' )
console.log( script.innerHTML )

function insert() {
  //insert the real templete
  Target1.appendChild( T1.content.cloneNode( true ) )
  //insert the fake template
  Target2.innerHTML += D1.innerHTML
}
<template id=T1>
  Real Template -
  <script>console.log( 'executed at each insertion' )</script>
</template>

<div hidden id=D1>
  Fake Template -
  <script>console.log( 'executed only at parsing' )</script>
</div>

<button onclick="insert()">insert</button>

<div id=Target1><div>
<div id=Target2><div>

Upvotes: 9

Ctc
Ctc

Reputation: 801

In short, the template tag is exactly what it sounds like. It is just a template for the JavaScript to create in the future.

It is slightly different from a hidden <div> though, but basically you are right and it can be faked with a hidden div

Imagine this scenario where you have a webpage with 2 inputs, one that enters your name and one that enters your age. By using a template tag to create a simple table, you can then use JavaScript to populate the table with your inputs, in the same page.

This article has a good read on it: https://www.sitepoint.com/html5-template-tag/

Upvotes: 1

Related Questions