<template> Tag
Overview
The <template> tag is a highly specialized element used to hold HTML code that you want to define now, but not actually render until later. When the browser parses a <template> tag, it validates the HTML inside it, but it creates it completely invisibly. It doesn't fetch images inside it, and it doesn't execute scripts inside it. It just holds the pristine structure in memory, waiting for JavaScript to clone it and inject it into the live DOM later. This is the absolute core architectural foundation behind modern Web Components.
Syntax
<!--
This HTML exists in the file, but is completely ignored
by the browser's visual renderer.
-->
<template id="product_card_template">
<article class="card">
<h2 class="title"></h2>
<p class="price"></p>
<button>Add to Cart</button>
</article>
</template>
<!-- Somewhere in your JavaScript: -->
<script>
// 1. Get the template
const template = document.getElementById('product_card_template');
// 2. Clone its exact structure (true means deep clone all children)
const newCard = template.content.cloneNode(true);
// 3. Inject data
newCard.querySelector('.title').textContent = 'Gaming Mouse';
newCard.querySelector('.price').textContent = '$59.99';
// 4. Inject it into the live DOM to make it visible
document.body.appendChild(newCard);
</script>Common Pitfalls
- Trying to query elements inside a template directly (e.g.,
document.querySelector('.title')). The contents of a template are trapped inside a special DocumentFragment. They literally do not exist in the live DOM. You must query them viatemplate.content.querySelector(). - Assuming templates are great for SEO. Search engines completely ignore the content inside a
<template>tag because it is deemed inactive. Never put SEO-critical information inside a template.
Interview Questions
<img> tag with a valid src is placed inside a <template>, will the browser download the image file on page load?No. The browser strictly halts all resource fetching and script execution inside a <template> until that template is explicitly cloned and attached to the live DOM via JavaScript.
Real-World Example
Defining a shadow DOM structure for a custom Web Component.
<!-- Defining a custom Web Component structure -->
<template id="my-button-template">
<style>
button { background: blue; color: white; border-radius: 8px; }
</style>
<button><slot></slot></button>
</template>Check Your Knowledge
Test your understanding of <template> Tag with these quick questions.