Rendering with tagged templates
Learn how an HTML tagged template renders: build a tiny html tag that parses once, keeps values as safe text, and updates only what changed, like lit-html.
- 01Explain what a tag function getsRead the strings array and the values apart, and know why the same template always passes the same frozen array.
- 02Build a tiny html rendererParse each template once into a
<template>, copy it, find its holes, and write only the values that changed. - 03Keep data safe and in the right placePut values in as text, attributes, properties, or listeners, never as markup, and keep holes out of places they can't go.
How do you render HTML with a tagged template?
Ravi wants the tea's name in bold on Leaf and Kettle's order ticket. So he writes the ticket as a string of HTML, and gives it to innerHTML. It works. Then Asha changes her order from small to large.
Here is that ticket. Press Change size.
<p id="ticket"></p><button>Change size</button><script type="module"> import { watch } from "./watch.js"; const ticket = document.querySelector("#ticket"); const order = { tea: "Oolong", size: "small" }; const draw = () => { ticket.innerHTML = `<b>${order.tea}</b>, ${order.size}`; }; draw(); const tea = ticket.querySelector("b"); watch(ticket); document.querySelector("button").addEventListener("click", () => { order.size = order.size === "small" ? "large" : "small"; draw(); console.log(`Same tea element: ${ticket.querySelector("b") === tea}`); });</script>- Line 6 is the order. Lines 7 to 9 draw it: one string of HTML, given to
innerHTML. - Line 11 keeps the bold element, the
<b>. Line 12 starts watching the ticket for changes. - Lines 14 and 15 change the size and draw again. Line 16 asks if the bold element is still the same one.
Press Change size. It prints Same tea element: false, then 2 nodes removed, 2 added.
Only the size changed. But innerHTML threw the whole ticket away, bold Oolong too, and built it again from a fresh parse. And if a tea's name held tags, they would become real elements. Can you write markup as easily as a string, but keep the nodes, and keep data as data?
Yes, with a tagged template. A tag function gets the fixed pieces of HTML and the values apart. A renderer such as lit-html parses the pieces into a <template> once and copies it. On every later render, it writes only the values that changed, as text or properties, never as HTML.
render() keep every node, and write only the two values that changed.Leaf and Kettle's order pads come printed: Tea, blank, Size, blank. The printer made them all at once. Ravi only writes in the blanks. When Asha changes her size, he crosses out one word and writes the new one. He doesn't print a new pad.
- In real life: The printed words on the pad
- In JavaScript: The template's fixed strings
- In real life: The blanks
- In JavaScript: The holes, written
${...} - In real life: What Ravi writes in a blank
- In JavaScript: A value
- In real life: Crossing out one word, not printing a new pad
- In JavaScript: Writing one changed value, not building the HTML again
Parse the fixed HTML once; write only the values. A tagged template hands a function the fixed strings and the values apart. The strings become a <template>, parsed once. Each value goes into its own hole, as text, and is written again only when it changes.
This lesson builds that renderer, a file called html.js. It uses JavaScript's tagged templates, and lesson 7.1's template element. At the end, the order ticket from lesson 18.1 renders with it.
Every page here prints its changes with the watch.js tab. It uses a MutationObserver: an object the browser calls with a list of changes to part of the page (the observers lesson).
export function watch(target) {
const observer = new MutationObserver((records) => {
for (const record of records) {
const node = record.target;
if (record.type === "characterData") console.log(`Text "${record.oldValue}" became "${node.data}"`);
if (record.type === "attributes") console.log(`Attribute ${record.attributeName} became "${node.getAttribute(record.attributeName)}"`);
if (record.type === "childList") console.log(`${record.removedNodes.length} nodes removed, ${record.addedNodes.length} added`);
}
});
observer.observe(target, { subtree: true, childList: true, characterData: true, characterDataOldValue: true, attributes: true });
}- Line 2 makes the observer. The browser calls it with a list of records, one per change.
- Lines 5 to 7 print each kind: a text that changed, an attribute that changed, or nodes added and removed.
- Line 10 watches everything inside the target, and keeps each text's old value.
How does an html tag turn strings into a template?
Our renderer, html.js, starts with the tag itself:
export function html(strings, ...values) {
return { strings, values };
}Line 2 hands back an object with the strings and the values. That's all. lit-html's tag does the same (lit-html.ts, lines 553 to 600). Lit's docs call the object a TemplateResult: "only a description of DOM" (Lit).
<script type="module"> import { html } from "./html.js"; const ticket = (order) => html`<p class=${order.size}><b>${order.tea}</b>, ${order.size}</p>`; const result = ticket({ tea: "Oolong", size: "small" }); console.log(`${result.strings.length} strings, values ${JSON.stringify(result.values)}`); console.log(`Paragraphs on the page: ${document.querySelectorAll("p").length}`);</script>- Line 3 is the ticket as a template function. It takes an order and returns a result.
- Line 4 calls it. Line 5 prints the result. Line 6 counts the paragraphs on the page.
It prints 4 strings, values ["small","Oolong","small"], then Paragraphs on the page: 0. Calling html made no element at all.
The browser can only parse HTML. So the next step joins the strings into one piece of HTML, with a marker in each hole: a little text the renderer can find again after parsing.
export function prepare(strings) {
let markup = strings[0];
strings.slice(1).forEach((text, hole) => {
const inAttribute = /=["']?$/.test(markup);
markup += inAttribute ? `hole-${hole}` : `<!--hole-${hole}-->`;
markup += text;
});
const template = document.createElement("template");
template.innerHTML = markup;
return template;
}- Line 2 starts with the first piece.
- Line 3 runs once per hole.
textis the piece after the hole, andholeits number, from 0. - Line 4 asks if the HTML so far ends with
=, or=". Then the hole is an attribute's value. - Line 5 adds the marker. An attribute gets plain text,
hole-0, because a comment can't sit inside a tag. Content gets a comment,<!--hole-1-->. The parser keeps a comment as its own node, so it's easy to find. - Line 6 adds the next piece. Lines 8 to 10 put the whole HTML in a new template, and return it.
<script type="module"> import { html, prepare } from "./html.js"; const ticket = (order) => html`<p class=${order.size}><b>${order.tea}</b>, ${order.size}</p>`; const template = prepare(ticket({ tea: "Oolong", size: "small" }).strings); console.log(template.innerHTML);</script>Line 4 prepares the ticket's strings, and line 5 prints the template's HTML: <p class="hole-0"><b><!--hole-1--></b>, <!--hole-2--></p>.
prepare() joins the pieces with a marker in each hole: a value for the attribute, and a comment for each text hole. render() keeps the <template> in a WeakMap under the strings array, so each template is parsed once.Line 9 uses innerHTML, but that's safe here. Only the strings reach it, and the strings come from your own code, never from data. Lit's design doc says the same of its template (Lit). A <template> also keeps its content inert: nothing in it loads or runs, as lesson 7.1 showed.
render() calls prepare() once per strings array. It keeps each template in a WeakMap: a map whose keys are objects, found by the object itself, not by what's inside it (WeakMap and WeakSet). lit-html keeps its own cache the same way, in templateCache (line 688).
Ravi stamps the shop's ticket layout onto every order slip. He carved the stamp once, from the printed design, with gaps for the tea and the size. Now each slip takes one press, and he writes in the gaps.
- In real life: Carving the stamp from the design
- In JavaScript:
prepare(): parsing the strings into a template - In real life: The gaps left in the stamp
- In JavaScript: The markers
- In real life: One press per slip
- In JavaScript: One copy of the template per container
- In real life: Writing in the gaps by hand
- In JavaScript:
render()filling the holes
How does render() find and fill the holes?
render(result, container) puts a result into a container: an element or a shadow root. It has two paths. The first time, it copies the template. Every time, it writes the values.
export function render(result, container) {
let instance = rendered.get(container);
if (instance?.strings !== result.strings) {
let template = templates.get(result.strings);
if (!template) {
template = prepare(result.strings);
templates.set(result.strings, template);
}
const copy = document.importNode(template.content, true);
instance = { strings: result.strings, holes: findHoles(copy, result.strings), values: [] };
container.replaceChildren(copy);
rendered.set(container, instance);
}
result.values.forEach((value, hole) => {
if (Object.is(instance.values[hole], value)) return;
instance.values[hole] = value;
instance.holes[hole](value);
});
}- Line 2 looks up what this container last rendered. Line 3 asks: is it a different template, or the first time?
- Lines 4 to 8 find the parsed template in the WeakMap. If it isn't there yet, they prepare it and keep it.
- Line 9 copies the template's content.
importNode()makes the copy in this page, so custom elements in it are ready at once (lesson 7.1). - Line 10 finds the holes in the copy, and starts an empty list of the values written. Line 11 puts the copy in the container. Line 12 remembers all of it.
- Lines 14 to 18 run every time. Line 15 skips a value that's the same as the last one written. Lines 16 and 17 write the others, and remember them.
Each hole is a small function that writes one value. Here is how the copy's holes are found:
function findHoles(copy, strings) {
const holes = [];
const walker = document.createTreeWalker(copy, NodeFilter.SHOW_COMMENT);
const comments = [];
while (walker.nextNode()) comments.push(walker.currentNode);
for (const comment of comments) {
if (!comment.data.startsWith("hole-")) continue;
const hole = Number(comment.data.slice(5));
const text = new Text();
comment.replaceWith(text);
holes[hole] = (value) => { text.data = value ?? ""; };
}
for (const element of copy.querySelectorAll("*")) {
for (const attribute of [...element.attributes]) {
if (!attribute.value.startsWith("hole-")) continue;
const hole = Number(attribute.value.slice(5));
element.removeAttribute(attribute.name);
const name = strings[hole].match(/([.@]?[\w-]+)=["']?$/)[1];
holes[hole] = attributeHole(element, name);
}
}
for (let hole = 0; hole < strings.length - 1; hole++) {
if (!holes[hole]) throw new Error(`html can't fill hole ${hole} where it is.`);
}
return holes;
}- Line 3 makes a TreeWalker: an object that visits the nodes under a root, one by one. This one visits only comments. Line 5 lists them all first, so the loop below can change the copy.
- Lines 7 and 8 skip other comments, and read the hole's number. Lines 9 and 10 swap the marker for an empty text node: a node that only shows characters.
- Line 11 is the hole: it sets that text node's data. A missing value shows nothing.
- Lines 13 to 17 look for attribute markers on every element, and remove each one. Line 18 reads the name as you wrote it, from the piece before the hole. The parser lowercases names, and a property name like
textContentneeds its capital letter. - Lines 22 to 24 stop with an error when a hole's marker is missing. A later section shows when.
function attributeHole(element, name) {
const key = name.slice(1);
if (name.startsWith(".")) return (value) => { element[key] = value; };
if (name.startsWith("@")) {
let listener = null;
return (value) => {
element.removeEventListener(key, listener);
listener = value;
element.addEventListener(key, listener);
};
}
return (value) => element.setAttribute(name, value);
}- Line 2 is the name without its first character.
- Line 3: a name that starts with a dot, like
.value, sets a property. - Lines 4 to 11: a name that starts with
@, like@click, is an event. Each new function replaces the last listener. - Line 12: any other name sets an attribute.
This page uses three kinds of hole, and renders twice:
<div id="out"></div><script type="module"> import { html, render } from "./html.js"; const out = document.querySelector("#out"); const view = (cups) => html` <input data-cups=${cups} .value=${cups}> <button @click=${() => console.log(`Order: ${cups} cups`)}>Order</button>`; render(view(3), out); render(view(4), out); out.querySelector("button").click(); console.log(out.querySelector("input").outerHTML); console.log(out.querySelector("input").value);</script>- Line 6 sets the
data-cupsattribute and thevalueproperty from the same number. - Line 7 gives the button a click listener that prints the cups.
- Lines 8 and 9 render with 3 cups, then 4. Line 10 clicks the button.
- Lines 11 and 12 print the input's markup and its value.
It prints Order: 4 cups once: the listener for 3 is gone. Then <input data-cups="4"> and 4. The attribute shows in the markup. The property doesn't, but the box holds 4. Press Order in the result, and it prints Order: 4 cups again.
A property hole is how you hand a component an object or an array, which an attribute can't hold. Lit's docs describe the same four kinds (Lit). The table sums them up. Read each row across.
| How you write the hole | What render() does | What the example shows |
|---|---|---|
${value} between tags, in the content. | It puts the value in a text node, with text.data. It never reads it as HTML. | The tea and the size in every ticket on this page. |
data-cups=${cups}, an attribute's whole value. | It calls setAttribute(). The value shows in the markup. | The printed input has data-cups="4". |
.value=${cups}, a dot before the name. | It sets the property: input.value = cups. Nothing shows in the markup. | The box shows 4, but the printed input has no value. |
@click=${fn}, an @ before the name. | It removes the last listener and adds the new one. | One click prints Order: 4 cups, not 3. |
Why are tagged template values safe from XSS?
Back to Ravi's second worry. A new tea arrives called <b>Earl Grey</b>, tags and all. This page puts one name in two ways: a string for innerHTML, and a hole. Pick a name:
<p id="string"></p><p id="holes"></p><script type="module"> import { html, render } from "./html.js"; const name = "Oolong"; const string = document.querySelector("#string"); const holes = document.querySelector("#holes"); string.innerHTML = `Tea: ${name}`; render(html`Tea: ${name}`, holes); console.log(`Elements from the string: ${string.children.length}`); console.log(`Elements from the hole: ${holes.children.length}`);</script>Both ways show Tea: Oolong. With no tags in the data, you can't see a difference.
- Line 5 is the name. Your choice changes it.
- Line 8 joins it into a string, and gives it to
innerHTML. Line 9 renders it into a hole. - Lines 10 and 11 count the elements each way made.
Oolong makes 0 elements both ways. With <b>Earl Grey</b>, the string makes 1: a real bold element. The hole makes 0, and shows the tags as letters. The image name prints the same counts, then The name ran code. That line came from the image's onerror attribute.
Here is why. Line 8 builds one string, and innerHTML parses all of it, the name included. Line 9 never parses the name. render() sets a text node's data, and a text node shows its characters as they are. Only the template's own strings are ever parsed.
Data that runs as code in your page is called XSS, cross-site scripting. Lesson 7.3 showed five ways a string can do it. The XSS lesson covers the rest.
At a busy café, the barista writes your name on your cup. Say "Free tea for everyone", and she writes exactly that. Nobody hands out free tea. The words are only your name, written down.
- In real life: The name you say at the counter
- In JavaScript: A value, like
<b>Earl Grey</b> - In real life: The barista writing it on the cup
- In JavaScript:
render()putting it in a text node - In real life: Nobody obeying what the cup says
- In JavaScript: The browser never parsing it as HTML
- In real life: The shop's own printed menu
- In JavaScript: The template's strings, which are HTML
Libraries keep the same rule. Lit's docs say only strings from template literals are parsed as HTML. To turn a string into markup, you must ask for it by name, with unsafeHTML(), and only for HTML you trust (Lit):
<p id="text"></p><p id="markup"></p><script type="module"> import { html, render } from "https://esm.sh/lit-html@3.3.3"; import { unsafeHTML } from "https://esm.sh/lit-html@3.3.3/directives/unsafe-html.js"; const name = "<b>Earl Grey</b>"; render(html`Tea: ${name}`, document.querySelector("#text")); render(html`Tea: ${unsafeHTML(name)}`, document.querySelector("#markup")); console.log(`b elements: ${document.querySelectorAll("#text b").length} and ${document.querySelectorAll("#markup b").length}`);</script>- Lines 4 and 5 load lit-html 3.3.3 and its unsafeHTML directive, from a CDN. The version is in the address.
- Line 7 renders the name in a hole. Line 8 wraps it in
unsafeHTML()first.
It prints b elements: 0 and 1. The name says "unsafe" right where it turns data into markup. uhtml does the same with unsafe() (uhtml).
One more guard: lit-html refuses a strings array you build yourself. A real one has a raw list, and lit-html checks for it. Its message says faking one "is effectively the same as calling unsafeHtml" (lines 753 to 780). Our tiny html.js doesn't check, so only call it as a tag.
How do you update only the values that changed?
Now the payoff. Here is the overview's ticket again, rendered with html.js. Press Change size, then Same again.
<div id="out"></div><button id="size">Change size</button> <button id="same">Same again</button><script type="module"> import { html, render } from "./html.js"; import { watch } from "./watch.js"; const out = document.querySelector("#out"); const order = { tea: "Oolong", size: "small" }; const ticket = () => html`<p class=${order.size}><b>${order.tea}</b>, ${order.size}</p>`; render(ticket(), out); const tea = out.querySelector("b").firstChild; watch(out); document.querySelector("#size").addEventListener("click", () => { order.size = order.size === "small" ? "large" : "small"; render(ticket(), out); console.log(`Same tea node: ${out.querySelector("b").firstChild === tea}`); }); document.querySelector("#same").addEventListener("click", () => render(ticket(), out));</script>- Line 8 is the ticket. The size is in two holes: the
classattribute, and the text. - Line 9 renders it. Line 10 keeps the text node that holds Oolong.
- Lines 13 to 15 change the size, render again, and check the Oolong node.
- Line 17 renders the same order again.
Press Change size. It prints Same tea node: true, then Attribute class became "large" and Text "small" became "large". Press Same again: nothing prints. No value changed, so nothing was written.
Compare that with the overview. There, innerHTML removed 2 nodes and added 2. Here, every node stayed. The Oolong text node is the same object, and only two values were written. Look back at the first picture: this is its right half.
An old train station board shows each train in little flaps. When one train is late, only the flaps of its time turn. Every other row stays still. Nothing is repainted from scratch.
- In real life: Each row of flaps
- In JavaScript: A hole
- In real life: The flaps that turn
- In JavaScript: The values that changed
- In real life: Rows that stay still
- In JavaScript: Nodes
render()leaves alone - In real life: The board knowing what each row shows
- In JavaScript:
render()keeping the last values
Why it matters: a node that isn't touched keeps what the browser keeps on it, like focus or selected text (build a tiny reactive UI). And the browser has less to do.
Is lit-html a virtual DOM?
No. A virtual DOM builds a tree of objects for the whole view on every render, then compares it with the last tree to find what changed (build a tiny reactive UI). lit-html never builds that tree. Its template is parsed, and its holes are found, already. On each render, it compares only the values: three, for this ticket. Lit's design doc says a part does no DOM work when its value is the same "by triple equal check" (Lit). Surma and Jake Archibald compare the two ways in VDOM vs lit-html.
It also never reads the page. This one proves it:
<div id="out"></div><script type="module"> import { html, render } from "./html.js"; const out = document.querySelector("#out"); const ticket = (tea) => html`<p>${tea}</p>`; render(ticket("Oolong"), out); out.querySelector("p").firstChild.data = "Assam"; render(ticket("Oolong"), out); console.log(`After the same value: ${out.textContent}`); render(ticket("Green tea"), out); console.log(`After a new value: ${out.textContent}`);</script>- Line 6 renders Oolong. Line 7 changes the text by hand, to Assam.
- Line 8 renders Oolong again. Line 10 renders a new value, Green tea.
It prints After the same value: Assam, then After a new value: Green tea. The last value written was Oolong, so line 8 changed nothing, and Assam stayed. lit-html works the same way. Its live() directive is for the rare case where the page can change under you: it compares with what the page holds now (Lit).
Where can a hole go in a template?
A hole only works where its marker survives parsing. Lit's docs name two places: an attribute's value, and an element's content (Lit). Try the same note in four places:
<div id="box"></div><script type="module"> import { html, render } from "./html.js"; const box = document.querySelector("#box"); const note = "Less sugar"; try { render(html`<p>${note}</p>`, box); console.log(`Rendered: ${box.innerHTML}`); } catch (error) { console.log(error.message); }</script>The marker comment sits inside the p. render() finds it and puts the note there as text.
- Line 5 is the note. Line 7 renders it, in the place you chose.
- Line 8 prints the container's HTML. Line 10 prints the error, if render() threw one.
In a paragraph, it prints Rendered: <p>Less sugar</p>. Inside a textarea or a template, it prints html can't fill hole 0 where it is. As the textarea's .value, it prints Rendered: <textarea></textarea>, and the box shows Less sugar.
A textarea's content is plain text, so the parser keeps the comment as words. A template's content lives in its own fragment, which the search never enters. In both cases, no marker is left to find. Lit's docs list the places to avoid:
- Tag names and attribute names, like
<${tag}>. Lit's development build throws (lines 860 to 866). - Inside a <template>. Lit's development build throws (lines 994 to 1005).
- Inside a <textarea>. Lit warns. Bind
.valueinstead. - Inside an element with contenteditable. Bind
.innerTextinstead. - Inside an HTML comment. Lit doesn't update it.
Our html.js stops with its error for the first three.
How do lit-html and uhtml render templates?
Both work the way html.js does. Here is the same ticket three ways. Press Change size in each:
<div id="out"></div><button>Change size</button><script type="module"> import { html, render } from "./html.js"; import { watch } from "./watch.js"; const out = document.querySelector("#out"); let size = "small"; const ticket = () => html`<p class=${size}><b>Oolong</b>, ${size}</p>`; render(ticket(), out); watch(out); document.querySelector("button").addEventListener("click", () => { size = size === "small" ? "large" : "small"; render(ticket(), out); });</script>Change size writes the class attribute and the size text. Oolong is never touched.
- Line 4 loads the renderer. lit-html and uhtml come from a CDN, at a pinned version.
- In the first two, line 8 is the ticket, and line 13 renders it again with the new size.
- In uhtml, line 7 makes a signal: a box that tells uhtml when its value changes. Line 9 renders the ticket. Line 12 sets the signal, and uhtml renders again by itself. Lesson 18.5 covers signals.
Our html.js and lit-html print Attribute class became "large", then Text "small" became "large". uhtml prints the same two, the text first: it walks its holes from the last to the first.
lit-html is the template part of Lit, which stage 8 teaches (Lit). uhtml is a smaller library with a JSX-like syntax (uhtml). Both keep each parsed template in a WeakMap under its strings array, and both skip a value that didn't change. Read each row across:
| What it does | Our html.js | lit-html 3.3.3 | uhtml 5.0.9 |
|---|---|---|---|
| Keeps each parsed template | In a WeakMap, by the strings array. | The same: templateCache, line 688. | The same: a WeakMap by the strings array. |
| Marks the holes | hole-0, and <!--hole-0--> in the content. | lit$ and random digits, so a marker never matches your own text (lines 349 to 356). | A comment, <!--◦-->. |
| Skips a value that didn't change | Yes, with Object.is(). | Yes, with !== (lines 1475 and 1476). | Yes, with !==. |
| Kinds of holes | Text, attributes, .properties, and @events. | Those, plus ?boolean attributes and element directives. | Those, plus ?toggle, aria, data, on events, key, and ref. |
| Turns a string into markup | Never. | Only inside unsafeHTML(). | Only inside unsafe(). |
| Nested templates and lists | No. | Yes. | Yes. |
| How you call it | render(result, container). | render(result, container). | render(container, () => result), then signals update it. |
The line numbers are in lit-html.ts at the lit@3.3.3 tag. Lists and keys come in lesson 18.3.
Is there a built-in templating API?
No. Every library builds its own, as html.js does. Two proposals would add one to the browser. Template Instantiation, from Apple, would fill a template's holes for you. DOM Parts, from Apple and Google engineers, would give the browser its own parts, like lit-html's. Neither is in any browser: Chrome has no ChildNodePart or createInstance(). Justin Fagnani, of the Lit team, argues the time is right for one in The time is right for a DOM templating API.
Rendering the kit's order ticket with html
Lesson 18.1's ReactiveTea calls update() once per batch of changes (lesson 18.1). That's the place to call render(). The kit now has two changes, in kitAfter182:
- tea-kit/html.js: this lesson's renderer, with comments.
- tea-kit/tea-ticket.js: its
update()renders the line with it.
update(changed) {
const milk = this.#milk === "none" ? "no milk" : `${this.#milk} milk`;
const extras = this.#extras.map((extra) => `, ${extra}`).join("");
render(html`${this.#tea}, ${this.#size}, ${milk}${extras}`, this.shadowRoot.querySelector("p"));
}- Line 2 words the milk, as before.
- Line 3 joins the extras into one piece of text, like ", honey".
- Line 4 renders four text holes into the ticket's line, in its shadow root. The line reads the same as in lesson 18.1.
<link rel="stylesheet" href="tea-kit/tokens.css"><tea-ticket tea="Oolong"></tea-ticket><p><button>Same again</button></p><script type="module"> import "./tea-kit/index.js"; import { watch } from "./watch.js"; const ticket = document.querySelector("tea-ticket"); await ticket.updateComplete; const line = ticket.shadowRoot.querySelector("p"); const tea = line.firstChild; watch(line); document.querySelector("button").addEventListener("click", async () => { ticket.size = "large"; ticket.milk = "oat"; await ticket.updateComplete; console.log(`Same tea node: ${line.firstChild === tea}`); });</script>- Line 8 waits for the first update. Lines 9 to 11 keep the line and its first text node, and watch the line.
- Lines 13 and 14 set two properties. Line 15 waits for the update.
Press Same again. It prints Text "small" became "large", Text "no milk" became "oat milk", then Same tea node: true. Press it again: only Same tea node: true. The values match, so no update runs.
The two lessons fit together. 18.1 made many sets into one update. This lesson makes one update write only what changed. Every other kit file stays as it was. custom-elements.json documents html.js and its three functions.
Common mix-ups
- "html`...` builds DOM." No. It returns the strings and the values. Only
render()builds or changes DOM. - "Two templates with the same text share a strings array." No. Each template in your code gets its own array. The same one comes back only when that template runs again.
- "render() parses the HTML on every call." No. It parses once per strings array. Later renders only compare values.
- "Any tagged template escapes HTML." No. The tag decides. A tag that joins the values into a string for
innerHTMLis as unsafe as that string. Safety comes from putting values in as text. - "lit-html is a virtual DOM." No. It never builds a tree to compare. It compares each hole's value with the last one it wrote.
- "render() makes the page match the template again." No. It doesn't read the page. A change made by hand stays until that value changes.
- "A hole can go anywhere in the markup." No. Only in content and attribute values. Not in tag names, attribute names, or inside a template or a textarea.
Practice exercises
Predict what the page prints, then run it.
<script type="module"> const tag = (strings) => strings; const card = (tea) => tag`<p>${tea}</p>`; const label = (tea) => tag`<p>${tea}</p>`; console.log(card("Oolong") === card("Assam"), card("Oolong") === label("Oolong"));</script><script type="module"> const tag = (strings) => strings; const card = (tea) => tag`<p>${tea}</p>`; const label = (tea) => tag`<p>${tea}</p>`; console.log(card("Oolong") === card("Assam"), card("Oolong") === label("Oolong"));</script>It prints true false. Both card calls run one template, so they get the same array. label's template sits elsewhere in the code, so it has its own array, even with the same text.
The name has tags in it. Predict what line 7 prints.
<div id="box"></div><script type="module"> import { html, render } from "./html.js"; const box = document.querySelector("#box"); const name = "<i>Assam</i>"; render(html`<p>Tea: ${name}</p>`, box); console.log(box.querySelectorAll("i").length, box.textContent);</script><div id="box"></div><script type="module"> import { html, render } from "./html.js"; const box = document.querySelector("#box"); const name = "<i>Assam</i>"; render(html`<p>Tea: ${name}</p>`, box); console.log(box.querySelectorAll("i").length, box.textContent);</script>It prints 0 Tea: <i>Assam</i>. The hole's text node shows the tags as letters, so there's no i element to count.
The page prints an error. Fix line 7. What does it print then?
<div id="box"></div><script type="module"> import { html, render } from "./html.js"; const box = document.querySelector("#box"); const note = "Less sugar"; try { render(html`<textarea>${note}</textarea>`, box); console.log(`Shows: ${box.querySelector("textarea").value}`); } catch (error) { console.log(error.message); }</script><div id="box"></div><script type="module"> import { html, render } from "./html.js"; const box = document.querySelector("#box"); const note = "Less sugar"; try { render(html`<textarea .value=${note}></textarea>`, box); console.log(`Shows: ${box.querySelector("textarea").value}`); } catch (error) { console.log(error.message); }</script>Line 7 now sets the textarea's value property through a hole on the tag. render() finds the marker, so it prints Shows: Less sugar.
Change tea prints 2 nodes removed, 2 added. Draw the ticket with html.js instead, by changing line 9. What does Change tea print then?
<p id="ticket"></p><button>Change tea</button><script type="module"> import { html, render } from "./html.js"; import { watch } from "./watch.js"; const ticket = document.querySelector("#ticket"); const order = { tea: "Oolong", size: "small" }; const draw = () => { ticket.innerHTML = `<b>${order.tea}</b>, ${order.size}`; }; draw(); watch(ticket); document.querySelector("button").addEventListener("click", () => { order.tea = "Assam"; draw(); });</script><p id="ticket"></p><button>Change tea</button><script type="module"> import { html, render } from "./html.js"; import { watch } from "./watch.js"; const ticket = document.querySelector("#ticket"); const order = { tea: "Oolong", size: "small" }; const draw = () => { render(html`<b>${order.tea}</b>, ${order.size}`, ticket); }; draw(); watch(ticket); document.querySelector("button").addEventListener("click", () => { order.tea = "Assam"; draw(); });</script>Line 9 now renders a template. The second draw finds the same template, compares the values, and writes only the tea: Text "Oolong" became "Assam". A second press prints nothing.
Rendering the same order twice prints Writes: 3. Fix render() in the html.js tab. What does the page print then?
<div id="out"></div><script type="module"> import { html, render } from "./html.js"; const out = document.querySelector("#out"); const ticket = (order) => html`<p class=${order.size}><b>${order.tea}</b>, ${order.size}</p>`; const order = { tea: "Oolong", size: "small" }; render(ticket(order), out); const observer = new MutationObserver(() => {}); observer.observe(out, { subtree: true, childList: true, characterData: true, attributes: true }); render(ticket(order), out); console.log(`Writes: ${observer.takeRecords().length}`);</script><div id="out"></div><script type="module"> import { html, render } from "./html.js"; const out = document.querySelector("#out"); const ticket = (order) => html`<p class=${order.size}><b>${order.tea}</b>, ${order.size}</p>`; const order = { tea: "Oolong", size: "small" }; render(ticket(order), out); const observer = new MutationObserver(() => {}); observer.observe(out, { subtree: true, childList: true, characterData: true, attributes: true }); render(ticket(order), out); console.log(`Writes: ${observer.takeRecords().length}`);</script>Only the html.js tab changes: line 75 skips a value that's the same as the last one written. Rendering the same order again writes nothing, so it prints Writes: 0.
?disabled=${soldOut} should add the attribute for true, and remove it for false. It prints true true. Make it work in the html.js tab. What does the page print then?
<div id="out"></div><script type="module"> import { html, render } from "./html.js"; const out = document.querySelector("#out"); const order = (soldOut) => html`<button ?disabled=${soldOut}>Order Oolong</button>`; render(order(true), out); const first = out.querySelector("button").disabled; render(order(false), out); console.log(first, out.querySelector("button").disabled);</script><div id="out"></div><script type="module"> import { html, render } from "./html.js"; const out = document.querySelector("#out"); const order = (soldOut) => html`<button ?disabled=${soldOut}>Order Oolong</button>`; render(order(true), out); const first = out.querySelector("button").disabled; render(order(false), out); console.log(first, out.querySelector("button").disabled);</script>Only the html.js tab changes. A ? name now toggles the attribute: added for true, removed for false. So the button turns back on, and the page prints true false.
Check your understanding
Question 1 of 8In our html.js and in lit-html, what does calling the
htmltag on a template give back?Choose an answer to see the explanation.
Question 2 of 8What does this list item template print when one function runs it twice?
Read the code, then predictconst tag = (strings) => strings; const item = (tea) => tag`<li>${tea}</li>`; console.log(item("Oolong") === item("Assam"));Choose an answer to see the explanation.
Question 3 of 8Why can render() keep its parsed templates in a WeakMap, keyed by the strings array?
Choose an answer to see the explanation.
Question 4 of 8What markup does prepare() make for this note and tea template?
Read the code, then predictJavaScriptconst note = "Less sugar"; const tea = "Oolong"; const template = prepare(html`<p title=${note}>${tea}</p>`.strings); console.log(template.innerHTML);Choose an answer to see the explanation.
Question 5 of 8A hole gets the value "<b>Earl Grey</b>". What shows on the page?
Choose an answer to see the explanation.
Question 6 of 8In the update page, Change size renders the ticket again with only the size changed. What does render() write?
Choose an answer to see the explanation.
Question 7 of 8Is lit-html a virtual DOM?
Choose an answer to see the explanation.
Question 8 of 8Where can't a hole go?
Choose an answer to see the explanation.
Key takeaways
- A tag function gets the fixed strings in one array, and the values apart. There is one more string than holes.
- One template expression passes the same frozen array every time it runs. A template with the same text elsewhere gets its own.
htmldoes no work.render()parses each strings array once into a<template>, with a marker in each hole, and keeps it in a WeakMap.- Each container gets one copy. Each hole becomes a function that writes a text, an attribute, a property, or a listener.
- Values go in as text, never as HTML. Turning a string into markup takes a named choice, like Lit's unsafeHTML().
- Later renders compare each value with the last one written, and touch only the holes that changed.
- lit-html is not a virtual DOM. It compares values, not trees, and never reads the page.
- Holes go in content and attribute values. Not in names, or inside a template or a textarea.
Remember the one-liner.
Parse the strings once, copy them once, and after that write only the values that changed, as text.
Sources
The facts on this page come from these docs, source files, talks, and posts:
- Template literals: tagged templates, MDN.
- Using lit-html standalone: rendering lit-html templates, Lit.
- Life of a lit-html render, at lit@3.3.3, Lit.
- lit-html.ts at lit@3.3.3: the html tag, Lit.
- lit-html.ts at lit@3.3.3: the template cache, Lit.
- lit-html.ts at lit@3.3.3: TemplateInstance._clone() and _update(), Lit.
- Expressions, Lit.
- Built-in directives: unsafeHTML, Lit.
- Built-in directives: live, Lit.
- MutationObserver, MDN.
- Document: createTreeWalker() method, MDN.
- VDOM vs lit-html, HTTP 203, Surma and Jake Archibald.
- Expressions: valid expression locations, Lit.
- µhtml (uhtml) 5.0.9: Syntax and Special Attributes, Andrea Giammarchi.
- uhtml 5.0.9: src/dom/index.js, the template cache, Andrea Giammarchi.
- DOM Parts proposal, WICG.
- HTML Template Instantiation proposal, WICG.
- The time is right for a DOM templating API, Justin Fagnani.
- browser-compat-data, MDN.
Support data comes from MDN's browser-compat-data. The TreeWalker and MutationObserver pages are on MDN too: createTreeWalker() and MutationObserver.
Coming next: Lists and keys. It renders a list of teas, and keeps each item's DOM when the list changes order.