Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • template is not rendered on screen
  • template does not make its way to the DOM
  • there is an additional content property which acts as a virtual element between the template and its contents

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.

The question is, is this correct? I ask because:

  • I just need to get it clear in my own mind
  • it would be relatively easy to fake one for nonsupporting browsers.

Thanks

like image 939
Manngo Avatar asked Jun 28 '16 01:06

Manngo


1 Answers

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 immedialtey.

    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>
like image 173
Supersharp Avatar answered Oct 24 '22 03:10

Supersharp