This method place the template's content into a hidden container. The main pitfall of this way is that the browser fetch resources from the template, even the image (in case below) is have not been used yet.
<div style="display: none"> <img src="https://static.zinoui.com/img/logo.png"> </div>
This approach use .innerHTML to inject the template content into the DOM. It would lead to possible XSS attacks.
<script type="text/template"> <img src="https://static.zinoui.com/img/logo.png"> </script>
That's the place where the native
<template> could help.
A method for declaring inert DOM subtrees in HTML and manipulating them to instantiate document fragments with identical contents. Part of the Web Components' set of standards.
<template>element can be placed into <head>, <body>, <frameset> and <colgroup>
Actually the template's content is not part of DOM until is used, e.g. styles will not apply, scripts will not run, HTML will not render, images will not download.
In order to use a template, first you need to clone it, then insert it into the DOM.
<template> <li> <a href=""></a> </li> </template> <ul></ul>
// Clone the fragment var template = document.querySelector('template'); var item = document.importNode(template.content, true); // Change the fragment var a = item.querySelector('a'); a.textContent = 'Test link'; a.href = 'https://www.example.com'; // Insert the fragment into the DOM document.querySelector('ul').appendChild(item);
Chrome 26+, Firefox 22+, Safari 7.1+, Opera 15+. For old browsers try polyfills like this JSFiddle.
The new HTML5 template element looks very promising and has a bright future since it solves the problems with current template approaches. Our working demo demonstrates use of template tag with live example.
Drop a comment below telling me what do you think about the HTML Templates. And don't forget to share with your colleagues. Thanks so much for reading.
Join our mailing list and stay tuned! Never miss out news about Zino UI, new releases, or even blog post.