template and slot
How the template element holds inert markup you clone on demand, and how slot lets a component place the content you give it, with fallbacks and slotchange.
template and slot
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- `<template>` holds markup the browser parses but does not render, load or run. Its children live in `template.content`, a document fragment, not in the page.
- Cloning `template.content` and inserting it is what activates it: in a test, an image inside the template was not requested until the clone was added, and a script inside it ran then.
- A `<slot>` is a hole in a shadow tree. Light-DOM children with a matching `slot="name"` fill the named slot, and everything else fills the default slot.
- Content inside a `<slot>` is fallback. It shows only when nothing is assigned, and `assignedNodes()` tells you what is assigned.
- Slotted content stays in the light DOM, so ordinary `querySelector` and page CSS still see it, while the shadow internals are hidden.
Markup you don’t want yet
Building a list of cards from data means making the same chunk of HTML many times. You can concatenate strings (and invite escaping bugs), call createElement thirty times, or keep an example in the page and copy it. The last is cleanest, but a hidden div still sits in the DOM, matches selectors, loads its images and runs its scripts.
<template> is the copy-me stamp. The parser reads it, but nothing in it is live. Think of a rubber stamp: the design exists, and nothing has been printed until you press it.
<template id="card">
<article class="card"><h3></h3><p></p></article>
</template>
<script>
const t = document.getElementById("card");
const node = t.content.cloneNode(true);
node.querySelector("h3").textContent = "Hello";
document.body.append(node);
</script>
What I measured
Chromium 159, Firefox 159 and a WebKit build gave the same results:
- The template had
offsetHeight0, andtemplate.children.lengthwas 0 whiletemplate.content.children.lengthwas 4. The markup lives in a fragment. document.querySelector('p.x')did not find the paragraph inside the template.- A
<script>in the template did not run on load. An<img>inside it triggered zero network requests. - After
content.cloneNode(true)was appended to the body, the image was requested once, the paragraph became findable and the script ran. Scripts in cloned template content are not marked as already run, which is worth knowing before you put one there.
Use textContent, not innerHTML, when filling clones with user data. The video from Steve Griffith, from 2017, shows this clone-and-fill workflow in plain JavaScript.
slot: holes in a shadow tree
Templates become powerful with <slot>. In a component with a shadow root, a slot marks where the host’s own children should appear. The shadow tree is the frame; the children you wrote between the host’s tags are the picture.
<my-card>
<span slot="title">Custom title</span>
Default body text
</my-card>
with a shadow tree of <h3><slot name="title">Untitled</slot></h3><div><slot>No body</slot></div>. In the test:
- The
titleslot’sassignedNodes()returned the span, and the unnamed slot returned the text node. - With no children,
assignedNodes()was empty andassignedNodes({ flatten: true })returned the fallback text “Untitled”. Fallback shows, but it isn’t assigned. - A slotted child’s
assignedSlotpointed at the slot. document.querySelector('h3')returned null, because the shadow tree is hidden from document queries, while the slotted span stayed in the light DOM.- Appending text to a host with a default slot fired
slotchangeonce.
Declarative shadow DOM does the same without script: <div><template shadowrootmode="open">…<slot></slot></template>light child</div> produced an open shadow root whose slot was assigned “light child” in all three engines. web-features lists declarative shadow DOM as Baseline, newly available since February 2024.
Depth on shadow DOM encapsulation, styling and events is in the frontend web components lesson. Here, remember only that slots are what makes components usable as ordinary HTML: authors write children, the component places them.
What the video covers
Steve Griffith’s “Using HTML5 Templates” (November 2017, about 10 minutes). Its description makes the case that writing JavaScript to build every piece of HTML does not scale, and introduces <template> as hidden markup you can clone and paste anywhere. That covers the first half of this lesson. It does not cover slot; dcode’s 2024 slots tutorial in further viewing does. I could not read a transcript, and 2017 is old, though template has not changed. The measurements above are mine.
Where this fits
This follows data attributes and leads to custom elements in HTML, where templates and slots become components.
Check yourself
Why does `document.querySelector('p.x')` find nothing for a `<p class="x">` inside a `<template>`?
The template's children belong to `template.content`, a separate fragment, not to the document. In a test the template element itself had no children and the content fragment had them all. Query `template.content` instead.
A template contains an `<img>`. When does the browser request the image?
Not until you clone the content and insert it into the document. In a test there were zero requests before the clone and one after.
A component has a named slot `title` with fallback text "Untitled", and you give it no title. What do `assignedNodes()` and `assignedNodes({flatten: true})` return?
The first is empty, because nothing is assigned. The flattened form returned the fallback text, "Untitled". Fallback is rendered but is not an assigned node.
You add child text to a custom element after it has rendered. How does the component notice?
Listen for `slotchange` on the slot. In a test it fired once after text was appended to the host. It fires for assignment changes, not for edits inside already assigned nodes.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.