completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

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.

By the end, you can
  • 01
    Explain what a tag function getsRead the strings array and the values apart, and know why the same template always passes the same frozen array.
  • 02
    Build a tiny html rendererParse each template once into a <template>, copy it, find its holes, and write only the values that changed.
  • 03
    Keep 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.

A ticket drawn with an HTML stringPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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.

Two halves, both after pressing Change size. Left, labelled innerHTML: two crossed-out cards, b: Oolong and text: , small, marked both thrown away. An arrow goes down to two new cards, b: Oolong and text: , large, marked both built again. Right, labelled html and render(): three cards, class: small, Oolong, and small. Arrows go down only from class: small to class: large and from small to large. Oolong has no arrow and is marked untouched.innerHTMLb: Oolongtext: , smallboth thrown awayb: Oolongtext: , largeboth built again2 nodes removed, 2 addedhtml and render()class: smallOolongsmalluntouchedclass: largeOolonglargesame nodestwo values written
The same click, two ways. innerHTML throws both nodes away and builds them again, Oolong included. html and render() keep every node, and write only the two values that changed.
Real-life analogyA printed order pad

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
The main idea

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).

watch.js: print each change in plain wordsJavaScript
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.

What does a tag function receive?

A template literal is a string in backticks. Its ${...} parts are blanks that JavaScript fills in. Put a function name right before the backtick, and it becomes a tagged template. The function is the tag. JavaScript doesn't build a string at all. It calls the tag with two things:

  • the fixed pieces of text, in one array, called the strings array;
  • the values, one argument each.
A tag that prints what it getsPop out in the code editor (opens in a new tab)JavaScript
function show(strings, ...values) {
  console.log(JSON.stringify(strings));
  console.log(JSON.stringify(values));
}
const order = { tea: "Oolong", size: "small" };
show`<p class=${order.size}><b>${order.tea}</b>, ${order.size}</p>`;
  • Line 1 is the tag. ...values collects every argument after the first into one array.
  • Lines 2 and 3 print both arrays as text.
  • Line 6 calls the tag: no brackets, just the name before the backtick.

Line 2 prints ["<p class=","><b>","</b>, ","</p>"]. Line 3 prints ["small","Oolong","small"].

Two crates. Left, labelled strings, holds four cards in order: 0: <p class=, 1: ><b>, 2: </b>, , and 3: </p>. Under it: four pieces, one more than the holes. Right, labelled values, holds three cards: 0: small, 1: Oolong, and 2: small. Under it: three values.0: <p class=1: ><b>2: </b>, 3: </p>stringsfour pieces, one more than the holes0: small1: Oolong2: smallvaluesthree values
The tag gets the fixed pieces in one array, and the values apart. Three holes cut the text into four pieces. Two holes hold the same value, small, so it comes twice.

Three holes cut the text into four pieces. There is always one more piece than holes, even when a piece is empty. The tag decides what to do with them. It can return anything, not only a string (MDN).

Is the strings array the same object every time?

Yes, for the same template. Run one template twice, then run two templates that look alike. Each choice changes only line 4:

Playground: one template, or two that look alike
Compare the strings arrays of two callsPop out in the code editor (opens in a new tab)HTML
<script type="module">  const tag = (strings) => strings;  const ticket = (tea) => tag`<p>${tea}</p>`;  const menu = ticket;  const first = ticket("Oolong");  const second = menu("Assam");  console.log(first === second);  console.log(Object.isFrozen(first));</script>
ResultLoading…
Try it yourself
The same strings array

menu is the ticket function itself, so both calls run the same template. The tag gets the very same array both times: true.

Only line 4 changes: menu is the same function, or a new one with the same text.
  • Line 2 is a tag that returns its strings array.
  • Line 3 is a template function. Line 4 makes menu: the same function, or a copy written the same way.
  • Line 7 asks if the two arrays are the same object. Line 8 asks if the array is frozen: locked, so nothing can change it.

With one template, it prints true, then true. With two templates, it prints false, then true.

Different values didn't matter. Same text didn't matter either. Only the place in the code matters. MDN says the tag gets "the exact same literal array" each time one template expression runs. It also says the array, and its raw list, are frozen (MDN).

Real-life analogyOrders clipped to their table

Ravi clips each order to the table it came from. Table 4 has the same clip on every visit. Table 7 may order the very same teas, but it has its own clip. Ravi finds an order by its table, not by what it says.

In real life: A table in the café
In JavaScript: One template expression in your code
In real life: Its clip, the same one every visit
In JavaScript: Its strings array, the same each time it runs
In real life: Table 7 ordering the very same thing
In JavaScript: Another expression with the same text: its own array
In real life: Finding an order by its table
In JavaScript: A WeakMap finding a template by its array

Why it matters: a frozen array that never changes makes a perfect name for a template. A renderer can parse the HTML once, and file the result under that array.

How does an html tag turn strings into a template?

Our renderer, html.js, starts with the tag itself:

html.js: the html tag does no workJavaScript
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).

A result is the strings and the values, and no DOMPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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.

html.js: prepare() joins the strings with a marker in each holeJavaScript
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. text is the piece after the hole, and hole its 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.
What prepare() makes of the ticketPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…

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>.

Top: four cards, the strings <p class=, ><b>, </b>, , and </p>. An arrow down, labelled join with a marker in each hole, to one wide card: <p class=hole-0><b><!--hole-1--></b>, <!--hole-2--></p>. An arrow down, labelled template.innerHTML, to a crate labelled templates, a WeakMap, which holds a card key: strings with an arrow to a card value: <template>. Under it: the same strings next time, no parsing.<p class=><b></b>, </p>join, with a marker in each hole<p class="hole-0"><b><!--hole-1--></b>, <!--hole-2--></p>template.innerHTMLkey: stringsvalue: <template>templates, a WeakMapthe same strings next time: no parsing
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).

Real-life analogyCarving a stamp once

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.

html.js: render() copies once, then writes the valuesJavaScript
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:

html.js: findHoles() turns each marker into a writing functionJavaScript
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 textContent needs its capital letter.
  • Lines 22 to 24 stop with an error when a hole's marker is missing. A later section shows when.
html.js: attributeHole() writes an attribute, a property, or a listenerJavaScript
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:

An attribute, a property, and an event holePop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • Line 6 sets the data-cups attribute and the value property 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.

The kinds of holes in html.js
How you write the holeWhat render() doesWhat 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:

Playground: the same name, in a string and in a hole
One name, put in two waysPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
Try it yourself
A plain name

Both ways show Tea: Oolong. With no tags in the data, you can't see a difference.

Only line 5 changes. The first line of the result is the string. The second is the hole.
  • 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.

Two halves, each starting from the same card, <b>Earl Grey</b>. Left, labelled a string and innerHTML: an arrow down to a crate labelled p holding two cards, text: Tea: and a shaded b element card, marked the data became markup. Right, labelled a hole: an arrow down to a crate labelled p holding two text cards, text: Tea: and text: <b>Earl Grey</b>, marked the data stayed text.a string and innerHTML<b>Earl Grey</b>text: Tea:b elementpthe data became markupa hole<b>Earl Grey</b>text: Tea:text: <b>Earl Grey</b>pthe data stayed text
The same name, two ways. Joined into a string for innerHTML, its tags become a real b element. Put in a hole, it becomes one text node, and the tags show as letters.

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.

Real-life analogyA name written on a cup

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):

lit-html: a name as text, and the same name with unsafeHTML()Pop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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.

The ticket rendered with html and render()Pop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • Line 8 is the ticket. The size is in two holes: the class attribute, 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.

Real-life analogyA departure board with flaps

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:

render() compares with what it wrote, not with the pagePop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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:

Playground: the same note in four places
Render a note, and print the result or the errorPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
Try it yourself
A hole in the content

The marker comment sits inside the p. render() finds it and puts the note there as text.

Only line 7 changes. The page prints what it rendered, or the error.
  • 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 .value instead.
  • Inside an element with contenteditable. Bind .innerText instead.
  • 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:

Playground: the same ticket with three renderers
A ticket whose size changesPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
Try it yourself
Our renderer

Change size writes the class attribute and the size text. Oolong is never touched.

Our html.js and lit-html share the same page, apart from line 4. uhtml updates through a signal.
  • 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:

Our html.js, lit-html, and uhtml
What it doesOur html.jslit-html 3.3.3uhtml 5.0.9
Keeps each parsed templateIn a WeakMap, by the strings array.The same: templateCache, line 688.The same: a WeakMap by the strings array.
Marks the holeshole-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 changeYes, with Object.is().Yes, with !== (lines 1475 and 1476).Yes, with !==.
Kinds of holesText, 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 markupNever.Only inside unsafeHTML().Only inside unsafe().
Nested templates and listsNo.Yes.Yes.
How you call itrender(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.
The kit ticket's update(), with html and render()JavaScript
  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.
The kit ticket: two sets, one update, two text writesPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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 innerHTML is 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

Exercise 1 · Warm-upSame array or not?

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>
ResultLoading…

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · Warm-upWhat does a hole show?

    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>
    ResultLoading…

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeFix the note box

      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>
      ResultLoading…

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · PracticeDraw the ticket with html

        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>
        ResultLoading…

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeSkip the values that didn't change

          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>
          ResultLoading…

          Answer, then press Check. Spacing and letter case don’t matter.

            Exercise 6 · ChallengeAdd boolean attribute holes

            ?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>
            ResultLoading…

            Answer, then press Check. Spacing and letter case don’t matter.

              Check your understanding

              The tagged template rendering quiz · 8 questionsScore: first tries count
              1. Question 1 of 8In our html.js and in lit-html, what does calling the html tag on a template give back?

                Choose an answer to see the explanation.

              2. Question 2 of 8What does this list item template print when one function runs it twice?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                const tag = (strings) => strings;
                const item = (tea) => tag`<li>${tea}</li>`;
                console.log(item("Oolong") === item("Assam"));

                Choose an answer to see the explanation.

              3. 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.

              4. Question 4 of 8What markup does prepare() make for this note and tea template?

                Read the code, then predictJavaScript
                const 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.

              5. Question 5 of 8A hole gets the value "<b>Earl Grey</b>". What shows on the page?

                Choose an answer to see the explanation.

              6. 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.

              7. Question 7 of 8Is lit-html a virtual DOM?

                Choose an answer to see the explanation.

              8. 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.
              • html does 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:

              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.

              CompleteFrontend Clear concepts. Working examples.