The Template Element
This time the use-case is about deferred activating HTML (eventually also including javascript) by using browser native mechanisms.
The aim is to speed up the web page initial load by separating HTML and functionality that is used later from the main part of the web page.
The typical way the SPA frontend frameworks like Angular, react, vue etc. handle this case is by loading and not executing javascript (bundle) files that will create the HTML and CSS by generated scripts.
The <template> tag
The browser offers the possibility to load html elements without beeing included in the document and allows loading javascript content that is not yet "executed". In short:
HTML can contain tags that are not in the DOM
The html tag that supports this is the <template>
tag.
<template id="card">
<div style="margin:2px;padding:2px;border: 1px solid green">
<h3>SHOW</h3>
<button onclick="hideContent(event)">Hide</button>
<script>
console.log('alive!');
</script>
</div>
</template>
Any html and any javascript inside this tag is not activated on page load.
Developing using a <template> tag
To get access to the inner parts the DOM element for the <template>
tag has a content
property that can be used for retrieving the inner DocumentFragment.
The <template>
tag is supported by the HTML editors so you can create html and script inside
with the full editor support. While developing something new this is a good place to store the not-yet activated
html and code and use the full support in the IDE.
To activate such a piece of code is done using some very simple coding:
function activateTemplate() {
const template = document.querySelector("template#card");
const clone = temp.content.cloneNode(true);
const ihObj = document.querySelector('span#insert-here');
ihObj.parentElement.insertBefore(clone, ihObj);
} // activateTemplate
By the insertBefore(...)
call the html elements and script elements will get activated,
will be part of the DOM in the browser and eventual script is executed.
The [Activate Template(1)] button is executing this wnd will include the inner content inside the playgroud area below. You can repeat this multiple times and remove it again because the content includes a [Hide] button.
A good practice here is to use a containing element and not add multiple elements in one template tag to make it easy to remove the activated code again.
When you look at the first example implementation you will see that the script code inside the template will be executed every time the template is used.
More to come
The innerHTML must not be loaded with the page and can be deferred. See 13 Defer Loading with Templates
There will be more features in this advent calendar collection using the template tag. come back. They will be linked here.
SHOW
See also
- https://www.w3schools.com/TagS/tag_template.asp
- https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template
- https://developer.mozilla.org/en-US/docs/Web/API/HTMLTemplateElement