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 screentemplate
does not make its way to the DOMcontent
property which acts as a virtual element between the template
and its contentsAside 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.
There are some major differences:
Script (<script>
) in a <template>
element is not executed immediately.
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.
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.
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
.
<template>
elements can be placed in the <head>
element.
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>