Videos
» npm install html-template-tag
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 usingquerySelector()on itscontentproperty.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 modifyinginnerHTML.<template>elements can be placed in the<head>element.You access the template content as a string using
.innerHTMLor 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>
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/