Since the accepted answer would represent overloading script method, I would like to suggest another which is, in my opinion, much cleaner and more secure due to XSS risks which come with overloading scripts.
I made a demo to show you how to use it in an action and how to inject one template into another, edit and then add to the document DOM.
<template id="mytemplate">
<style>
.image{
width: 100%;
height: auto;
}
</style>
<a href="#" class="list-group-item">
<div class="image">
<img src="" />
</div>
<p class="list-group-item-text"></p>
</a>
</template>
// select
var t = document.querySelector('#mytemplate');
// set
t.content.querySelector('img').src = 'demo.png';
t.content.querySelector('p').textContent= 'demo text';
// add to document DOM
var clone = document.importNode(t.content, true); // where true means deep copy
document.body.appendChild(clone);
+Its content is effectively inert until activated. Essentially, your markup is hidden DOM and does not render.
+Any content within a template won't have side effects. Scripts don't run, images don't load, audio doesn't play ...until the template is used.
+Content is considered not to be in the document. Using document.getElementById()
or querySelector()
in the main page won't return child nodes of a template.
+Templates can be placed anywhere inside of <head>
, <body>
, or <frameset>
and can contain any type of content which is allowed in those elements. Note that "anywhere" means that <template>
can safely be used in places that the HTML parser disallows.
Browser support should not be an issue but if you want to cover all possibilities you can make an easy check:
To feature detect
<template>
, create the DOM element and check that the .content property exists:
function supportsTemplate() {
return 'content' in document.createElement('template');
}
if (supportsTemplate()) {
// Good to go!
} else {
// Use old templating techniques or libraries.
}
<script>
tag has display:none
by default."text/javascript"
..innerHTML
. Run-time string parsing of user-supplied data can easily lead to XSS vulnerabilities.Full article: https://www.html5rocks.com/en/tutorials/webcomponents/template/#toc-old
Useful reference: https://developer.mozilla.org/en-US/docs/Web/API/Document/importNode http://caniuse.com/#feat=queryselector
CREATING WEB COMPONENTS Creating custom web components tutorial using HTML templates by Trawersy Media: https://youtu.be/PCWaFLy3VUo