FE·17
DOM & Browser APIs
Working with the live document and the platform's built-in APIs: traversal, events and delegation, the four observers, fetch and URLs, history, clipboard, Web Crypto, storage, workers, real-time channels, notifications and files.
Start here: making pages interactive with the DOM
The DOM is a tree of objects you can change
When the browser parses HTML, every element becomes a JavaScript object in a tree (chapter 12). The document object is the root of that tree, and through it your code can find any element, read it, change it, add new ones and remove old ones. Whatever you change, the browser re-renders. That's the entire mechanism behind interactive pages.
Finding elements
const heading = document.querySelector("h1"); // the first element matching a CSS selector
const form = document.querySelector("#add-form"); // by id
const items = document.querySelectorAll("#list li"); // all matches (a NodeList; use for…of or [...items])
const firstLi = document.querySelector("#list li:first-child");
querySelector takes the same selectors as CSS (chapter 14), so there's one language to learn. It returns null if nothing matches, which is the source of the Start Here chapter's "Cannot read properties of null" error.
Reading and changing content
heading.textContent = "Shopping list"; // replace the text inside
heading.classList.add("highlight"); // add a CSS class (also remove, toggle, contains)
heading.style.color = "crimson"; // an inline style; prefer toggling classes
input.value; // what's typed in a form field (a string)
link.href = "/menu"; // properties mirror most attributes
button.dataset.action; // reads data-action="…" (custom data attributes)
button.disabled = true;
There are two ways to put text in an element, and the difference matters for security:
textContenttreats the value as plain text. Whatever the user typed, even something that looks like HTML, is displayed literally.innerHTMLparses the value as HTML. If any part of it came from a user, they can inject elements and run their own script (cross-site scripting, chapter 28).
The lab inserts the same user input, <img src="x" onerror="…">, both ways: with textContent it shows as text; with innerHTML it creates an image whose error handler runs the attacker's code. Use textContent for anything that came from a user or a server.
Creating and removing elements
const li = document.createElement("li"); // a new, detached element
li.textContent = "Toor dal";
list.append(li); // attach it: now it's on the page
li.remove(); // and take it away again
append accepts several nodes at once (li.append(span, button)); prepend, before, after and replaceWith place nodes elsewhere.
Events: running code when something happens
The browser fires events for everything users do (clicks, key presses, typing, scrolling, submitting) and for things that happen (a page finished loading, an image failed). You register a function to run when an event happens on an element:
button.addEventListener("click", event => {
console.log("clicked", event.target); // the event object describes what happened
});
input.addEventListener("input", () => preview.textContent = input.value); // fires on every change
form.addEventListener("submit", event => {
event.preventDefault(); // stop the browser's default action (submitting = loading a page)
// handle it in JavaScript instead
});
Common events: click, input (a field's value changed), change (committed: a checkbox ticked, a select chosen), submit, keydown, focus/blur, pointerdown/pointermove, scroll, DOMContentLoaded. Listen for submit on the form rather than click on its button: it also fires when the user presses Enter, and works with keyboard and assistive technology.
Bubbling and event delegation
An event on an element doesn't stay there: after reaching its target, it bubbles up through every ancestor, all the way to document. Click a button inside a list item inside a list, and listeners on the button, the item and the list all hear it, in that order. event.target is always the element where it started.
That makes event delegation possible: instead of attaching a listener to every button (including ones you'll add later), attach one listener to their container and work out which button was clicked:
list.addEventListener("click", event => {
const button = event.target.closest("button"); // the nearest button at or above where the click happened
if (!button) return; // a click on empty space in the list
// handle it
});
Putting it together: a shopping list
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Shopping list</title>
<style>
.done span { text-decoration: line-through; color: #888; }
li { display: flex; gap: .5rem; align-items: center; }
</style>
</head>
<body>
<h1>Shopping list</h1>
<form id="add-form">
<label for="item">New item</label>
<input id="item" name="item" required>
<button>Add</button>
</form>
<ul id="list"></ul>
<p id="count">0 items left</p>
<script type="module">
const form = document.querySelector("#add-form");
const input = document.querySelector("#item");
const list = document.querySelector("#list");
const count = document.querySelector("#count");
function updateCount() {
const left = list.querySelectorAll("li:not(.done)").length;
count.textContent = `${left} item${left === 1 ? "" : "s"} left`;
}
form.addEventListener("submit", event => {
event.preventDefault(); // stop the browser's normal form submission (a page load)
const li = document.createElement("li");
const span = document.createElement("span");
span.textContent = input.value; // textContent: the text is treated as text, never as HTML
const done = document.createElement("button");
done.type = "button"; done.textContent = "Done"; done.dataset.action = "toggle";
const remove = document.createElement("button");
remove.type = "button"; remove.textContent = "Remove"; remove.dataset.action = "remove";
li.append(span, done, remove);
list.append(li);
input.value = "";
input.focus();
updateCount();
});
// one listener on the list handles clicks on every button inside it, even ones added later
list.addEventListener("click", event => {
const button = event.target.closest("button");
if (!button) return;
const li = button.closest("li");
if (button.dataset.action === "toggle") li.classList.toggle("done");
if (button.dataset.action === "remove") li.remove();
updateCount();
});
</script>
</body>
</html>
Driven in Chromium: add three items (the third a would-be attack), mark the first done, remove the second:
count: 2 items left
items: [ '[x] Rice (5 kg)', '[ ] <img src=x onerror=alert(1)>' ]
count: 1 item left | img elements created: 0
list HTML of first item: <li class="done"><span>Rice (5 kg)</span><button type="button" data-action="toggle">Done</button>…</li>
Every piece of this section is in there: finding elements, preventDefault on submit, creating elements with textContent (the malicious item stayed harmless text), classes for state, delegation for buttons that didn't exist when the listener was added, and keeping the counter in sync. Notice the weak spot, too: the page is the data. To count items left, the code queries the DOM. As apps grow, keeping the screen consistent with the data by hand becomes the main source of bugs, which is the problem UI frameworks solve (chapter 21): you keep the data in JavaScript and the framework updates the DOM to match.
The rest of the browser's toolbox
The DOM is one of many browser APIs: objects the browser gives your JavaScript. The full-depth sections cover each; here's the map:
| You want to… | API |
|---|---|
| talk to a server | fetch, WebSocket, EventSource |
| remember data | localStorage, IndexedDB (chapter 12) |
| react when elements appear, resize or change | IntersectionObserver, ResizeObserver, MutationObserver |
| run code off the main thread | Web Workers (chapter 29) |
| copy and paste, share, notify | Clipboard, Web Share, Notifications |
| work with files the user picks | File, Blob, FileReader, the File System Access API |
| do cryptography | Web Crypto (crypto.subtle, crypto.randomUUID()) |
How deep to go in the DOM and browser APIs
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Name the DOM methods, event types and major browser APIs |
| L2 | Build interactive pages: query, create, update, handle events and forms, fetch data |
| L3 | Explain the event path (capture, target, bubble), default actions, observers' timing, the cost of DOM writes and layout reads |
| L4 | Diagnose layout thrashing, leaking listeners, stale closures, observer loops and XSS from DOM sinks |
| L5 | Choose the right API (observers, workers, storage, streaming) and design component boundaries |
| L6 | Operate DOM-heavy apps at scale: performance budgets, Trusted Types, API support across browsers |
The DOM in practice
Traversal and querying
// Querying: CSS selectors, so everything from chapter 14 works
document.querySelector("#cart .item.active"); // first match or null
document.querySelectorAll("li[data-sku]"); // STATIC NodeList (a snapshot): iterable, has forEach
document.getElementById("app"); // fastest for ids
el.closest(".card"); // nearest ancestor (or self) that matches: crucial for delegation
el.matches(":focus-visible"); // does el match a selector?
// Relationships: element-only versions skip text and comment nodes
el.parentElement; el.children; el.firstElementChild; el.lastElementChild;
el.nextElementSibling; el.previousElementSibling;
el.childNodes; // ALL nodes including whitespace text: rarely what you want
el.contains(other);
// Live vs static collections
const live = document.getElementsByClassName("row"); // HTMLCollection: LIVE, updates as the DOM changes
const snap = document.querySelectorAll(".row"); // NodeList: static
Live collections change while you loop over them. Removing elements from getElementsByClassName results inside a for loop skips every other one. Prefer querySelectorAll, or convert with Array.from.
Creating and changing the DOM
const li = document.createElement("li");
li.className = "item";
li.dataset.sku = "SOCK-42"; // → data-sku="SOCK-42"
li.textContent = userInput; // SAFE: treated as text
// li.innerHTML = userInput; // DANGEROUS: parses HTML → XSS (chapter 28)
list.append(li, "trailing text"); // append/prepend/before/after/replaceWith accept nodes or strings
list.replaceChildren(...newItems); // clear and fill in one operation
li.remove();
// Batch many inserts off-DOM, then attach once
const frag = document.createDocumentFragment();
for (const p of products) frag.append(renderRow(p));
table.tBodies[0].append(frag);
// Templates: inert markup cloned efficiently
const tpl = document.querySelector("#row-template");
const row = tpl.content.cloneNode(true);
row.querySelector(".name").textContent = product.name;
el.classList.add("open"); el.classList.toggle("active", isActive); el.classList.replace("a", "b");
el.setAttribute("aria-expanded", "true"); el.toggleAttribute("hidden", !visible);
el.style.setProperty("--progress", `${pct}%`); // set custom properties, not dozens of inline styles
textContent versus innerText versus innerHTML: textContent returns or sets raw text and is fast. innerText is rendering-aware: it respects CSS visibility and line breaks, and forces a layout when read. innerHTML parses HTML, so use it only with trusted or sanitised content, or use the setHTML() Sanitizer API where available.
Every DOM write may invalidate style and layout (chapter 18). Interleaving reads like offsetHeight with writes in a loop causes layout thrashing. Batch reads, then writes. Frameworks like React and Angular exist largely to manage DOM updates for you (chapters 22 and 23).
Events
An event is a notification that something happened: user input, network activity, lifecycle changes, media, and custom application events.
button.addEventListener("click", onClick);
button.addEventListener("click", onClick, {
once: true, // auto-remove after the first call
passive: true, // promises not to call preventDefault (lets scrolling start immediately)
capture: false, // listen in the bubble phase (the default)
signal: controller.signal // remove when the signal aborts: easy cleanup of many listeners at once
});
button.removeEventListener("click", onClick); // must be the SAME function reference
function onClick(event) {
event.type; // "click"
event.target; // the element where the event originated (maybe a child <span>)
event.currentTarget; // the element this listener is attached to
event.preventDefault(); // cancel the default action: following a link, submitting a form, checking a box
event.stopPropagation(); // stop it travelling further (use rarely: it breaks delegation and analytics)
event.isTrusted; // true if generated by the user, not dispatchEvent
}
// Custom events: decoupled communication between components
el.dispatchEvent(new CustomEvent("cart:add", { detail: { sku: "SOCK-42" }, bubbles: true, composed: true }));
document.addEventListener("cart:add", (e) => updateBadge(e.detail.sku));
Prefer modern input events: Pointer Events (pointerdown, pointermove, pointerup) unify mouse, touch and pen. Use click for activation, since it also fires for keyboard Enter and Space on buttons. Use keydown with event.key (not the deprecated keyCode), plus input and change for form fields. Use beforeinput for rich-text editing.
Mark scroll and touch listeners as passive so the browser doesn't have to wait for your handler before it can scroll. Browsers default touchstart and wheel listeners on the document to passive for this reason.
Event propagation
DOM events travel in three phases:
- Capture phase: from
windowdown through each ancestor to the target's parent. Listeners registered with{ capture: true }run here. - Target phase: at the target itself.
- Bubble phase: back up from the target to
window. Normal listeners run here.
Most events bubble, but not all of them: focus, blur, mouseenter, mouseleave, load and scroll (on elements) don't. Use focusin/focusout and pointerover/pointerout when you need bubbling versions. stopPropagation() stops the event moving between elements. stopImmediatePropagation() also stops other listeners on the same element.
Event delegation
Because events bubble, one listener on a common ancestor can handle events for any number of children, including children added later:
// Instead of one listener per row (thousands of listeners, re-added every time rows change)…
document.querySelector("#orders").addEventListener("click", (e) => {
const btn = e.target.closest("button[data-action]"); // find the button even if an icon <svg> inside was clicked
if (!btn || !e.currentTarget.contains(btn)) return;
const row = btn.closest("tr");
switch (btn.dataset.action) {
case "cancel": cancelOrder(row.dataset.id); break;
case "track": trackOrder(row.dataset.id); break;
}
});
Delegation saves memory, handles dynamic content automatically, and simplifies cleanup. React (since 17) attaches its listeners at the root container rather than on each element, and you write onClick on elements as if they were per-element. Angular binds per element by default.
Observers
The platform provides four observer APIs. Each replaces an expensive polling or event-based pattern with a batched, efficient callback.
MutationObserver
MutationObserver reports DOM changes: children added or removed, attribute changes, and text changes. Callbacks are delivered as microtasks in batches, after the mutating script finishes.
const mo = new MutationObserver((records) => {
for (const r of records) {
if (r.type === "childList") r.addedNodes.forEach(n => n.nodeType === 1 && enhance(n));
if (r.type === "attributes") console.log(`${r.attributeName} changed on`, r.target);
}
});
mo.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ["data-state"] });
// later: mo.disconnect();
Uses: enhancing third-party or CMS-inserted content, browser extensions, testing utilities (Testing Library's waitFor), editors, and syncing with code you don't control. Observing subtree on a large, busy DOM is expensive, so scope it narrowly.
IntersectionObserver
IntersectionObserver reports when elements enter or leave the viewport (or another scroll container), asynchronously and off the main thread's critical path. It replaces scroll listeners that call getBoundingClientRect() on every scroll event, which forces layout each time.
const io = new IntersectionObserver((entries) => {
for (const e of entries) {
if (e.isIntersecting) {
loadMore(); // infinite scroll sentinel
io.unobserve(e.target);
}
}
}, { root: null, rootMargin: "200px 0px", threshold: 0 }); // fire 200px before it's visible
io.observe(document.querySelector("#sentinel"));
Uses: lazy-loading images and components (native loading="lazy" covers images and iframes), infinite scroll, scroll-spy navigation, impression analytics ("was this ad 50% visible for 1 s?"), pausing animations or video when they're off-screen, and triggering reveal animations (or use CSS scroll-driven animations, chapter 14).
ResizeObserver
ResizeObserver reports changes to an element's size, whatever caused them: a window resize, a sidebar collapsing, content loading, a font swap. That makes it the JavaScript counterpart of container queries:
const ro = new ResizeObserver((entries) => {
for (const e of entries) {
const { inlineSize: width } = e.contentBoxSize[0];
chart.resize(width); // charts, canvases and virtualised lists need their real size
}
});
ro.observe(chartContainer);
Callbacks run after layout, before paint. Changing an observed element's size inside the callback can cause loops, which browsers limit with the "ResizeObserver loop completed with undelivered notifications" error. Use CSS container queries for styling, and ResizeObserver only when JavaScript needs the size: canvas, charts, virtualisation, text fitting.
PerformanceObserver
PerformanceObserver subscribes to performance timeline entries as they're recorded. It's how Core Web Vitals and Real User Monitoring (RUM) are measured in the field (chapters 27 and 32):
new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
console.log(entry.entryType, entry.name, entry.startTime, entry.duration);
}
}).observe({ type: "largest-contentful-paint", buffered: true }); // buffered: include earlier entries
// Other entry types: "navigation", "resource", "paint", "longtask", "long-animation-frame" (LoAF),
// "event" (interaction timing → INP), "layout-shift" (CLS), "element", "mark", "measure"
performance.mark("search:start");
await runSearch();
performance.measure("search", "search:start"); // shows up in DevTools Performance panel too
In practice, use Google's web-vitals library, which handles the many edge cases in computing LCP, INP and CLS correctly, and send results to your analytics with navigator.sendBeacon.
Networking and navigation APIs
Fetch
fetch is the modern HTTP API: promise-based, streaming, and built on the Fetch standard's Request and Response objects, which are also used in service workers, Node, Deno, Bun and edge runtimes.
const res = await fetch("/api/orders", {
method: "POST",
headers: { "Content-Type": "application/json", "Idempotency-Key": crypto.randomUUID() },
body: JSON.stringify({ sku: "SOCK-42", qty: 2 }),
credentials: "same-origin", // "omit" | "same-origin" (default) | "include" (send cookies cross-origin)
mode: "cors", // "cors" | "same-origin" | "no-cors" (opaque response)
cache: "no-store", // interacts with the HTTP cache (chapter 19)
signal: AbortSignal.timeout(8000),
keepalive: true, // survives page unload (analytics beacons)
priority: "high", // fetch priority hint
});
if (!res.ok) { // ⚠ fetch only REJECTS on network failure; 404/500 RESOLVE
const problem = await res.json().catch(() => null); // RFC 9457 Problem Details from Spring etc.
throw new HttpError(res.status, problem?.detail ?? res.statusText);
}
const order = await res.json(); // or .text(), .blob(), .arrayBuffer(), .formData(), res.body (stream)
Fetch gotchas:
- HTTP errors don't reject. A 404 or 500 resolves normally with
res.ok === false. Always checkres.ok. Axios, by contrast, rejects on non-2xx. - A body can be read once. Use
res.clone()if you need it twice (service workers do this). - No timeout by default: pass
AbortSignal.timeout()(chapter 15). - Cookies cross-origin need
credentials: "include"and the right CORS headers (chapter 19). - Streaming:
res.bodyis aReadableStream. You can process large or slow responses incrementally, like AI token streams or NDJSON. Request body streaming (duplex: "half") is supported in Chromium.
Compared with backend HTTP clients: Java's HttpClient (with sendAsync returning CompletableFuture) and Spring's RestClient/WebClient, Go's http.Client (with context for cancellation and a Timeout field), and Rust's reqwest. They all share the same concerns of connection pooling, timeouts, retries and status handling (Vol. 1 ch. 9).
URL and URLSearchParams
const url = new URL(location.href);
url.searchParams.get("page"); // "2" or null
url.searchParams.set("sort", "price-desc");
url.searchParams.delete("debug");
history.replaceState(null, "", url); // update the address bar without navigating
const params = new URLSearchParams({ q: "red socks", page: "1" });
params.toString(); // "q=red+socks&page=1"
fetch(`/api/search?${params}`);
for (const [k, v] of params) { /* iterate, preserving repeated keys */ }
params.getAll("tag"); // ["a", "b"] for ?tag=a&tag=b
URL.canParse(input); // validate without try/catch
URL.parse(input); // returns URL or null (newer)
URL state is a first-class kind of state (chapter 25). Filters, sort order, pagination, selected tab and search query should live in the URL, so views are bookmarkable, shareable and restorable with the back button. Since a user can type anything into the URL, validate query parameters with a schema (chapter 16).
History and the Navigation API
The History API (pushState, replaceState, the popstate event) and the newer Navigation API (chapter 12) let a single-page app change the URL and handle back and forward without reloading:
function navigate(path) {
history.pushState({ path }, "", path); // new history entry, no reload
render(path);
}
window.addEventListener("popstate", (e) => render(location.pathname)); // back/forward
// pushState does NOT fire popstate; your router must render explicitly after pushing.
Routers (React Router, TanStack Router, Angular Router, Vue Router) wrap these APIs. Responsibilities the browser no longer handles once you intercept navigation: scroll restoration (history.scrollRestoration = "manual" plus your own logic), focus management (move focus to the new page's heading or main, and announce the route change, chapter 20), document title updates, and loading and error states.
Clipboard
The asynchronous Clipboard API works in secure contexts and generally needs a user gesture for writing:
copyButton.addEventListener("click", async () => {
try {
await navigator.clipboard.writeText(codeBlock.textContent);
showToast("Copied");
} catch {
selectText(codeBlock); // fallback: select and let the user press Ctrl+C
}
});
const text = await navigator.clipboard.readText(); // read needs permission (Chromium prompts; Safari/Firefox show a paste menu)
await navigator.clipboard.write([new ClipboardItem({ "image/png": pngBlob })]); // rich content
document.addEventListener("paste", (e) => { // the paste EVENT gives data without a permission prompt
const files = [...e.clipboardData.files]; // e.g. pasted screenshots
const html = e.clipboardData.getData("text/html"); // sanitise before inserting!
});
document.execCommand("copy") is deprecated, though still around as a fallback.
Web Crypto
crypto.getRandomValues() and crypto.randomUUID() produce cryptographically secure randomness and work everywhere. crypto.subtle (SubtleCrypto, secure contexts only) provides real cryptographic primitives, implemented natively:
const id = crypto.randomUUID(); // v4 UUID: never Math.random() for IDs or tokens
// SHA-256 digest (e.g. subresource integrity, content hashing, PKCE code challenge)
async function sha256Hex(text) {
const bytes = new TextEncoder().encode(text);
const hash = await crypto.subtle.digest("SHA-256", bytes);
return [...new Uint8Array(hash)].map(b => b.toString(16).padStart(2, "0")).join("");
}
// AES-GCM encryption with a non-extractable key
const key = await crypto.subtle.generateKey({ name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"]);
const iv = crypto.getRandomValues(new Uint8Array(12)); // NEVER reuse an IV with the same key
const ciphertext = await crypto.subtle.encrypt({ name: "AES-GCM", iv }, key, new TextEncoder().encode("secret"));
It supports SHA-1/256/384/512 digests, HMAC, AES-GCM/CBC/CTR, RSA-OAEP, RSA-PSS, ECDSA, ECDH, Ed25519 and X25519 (now in all major engines), and PBKDF2/HKDF key derivation. Uses: the PKCE code challenge in OAuth (chapter 28), end-to-end encrypted apps, signing, and integrity checks. Keys can be non-extractable (JavaScript can use them but never read the raw bytes) and stored in IndexedDB. Don't invent your own cryptography. Don't treat client-side crypto as protection against your own server or an XSS attacker, since the attacker controls the JavaScript. And never use Math.random() for anything security-related.
Storage and data APIs
IndexedDB
IndexedDB is the browser's transactional object database: asynchronous, origin-scoped, with indexes and large capacity. Its raw API is event-based and verbose, so most code uses a thin promise wrapper such as idb, or Dexie:
import { openDB } from "idb";
const db = await openDB("shop", 2, {
upgrade(db, oldVersion) { // schema migrations run here, versioned
if (oldVersion < 1) {
const store = db.createObjectStore("orders", { keyPath: "id" });
store.createIndex("byDate", "createdAt");
}
if (oldVersion < 2) db.createObjectStore("drafts", { keyPath: "id" });
},
});
await db.put("orders", { id: "o_1", total: 899, createdAt: Date.now() });
const recent = await db.getAllFromIndex("orders", "byDate", IDBKeyRange.lowerBound(Date.now() - 864e5));
const tx = db.transaction(["orders", "drafts"], "readwrite"); // multi-store atomic transaction
await Promise.all([tx.objectStore("orders").delete("o_1"), tx.objectStore("drafts").clear(), tx.done]);
Concepts that map onto databases (Vol. 4 covers databases properly): object stores are like tables (they hold structured-clone values, chapter 15), key paths are primary keys, indexes are secondary indexes (B-trees, Vol. 1 ch. 3), transactions are scoped to stores (readonly or readwrite), and versioned upgrades are schema migrations. A gotcha: a transaction auto-commits as soon as no requests are pending, so awaiting unrelated work (such as a fetch) in the middle of a transaction makes it close early.
Uses: offline-first apps (with service workers, chapter 29), caching API data, drafts, large client-side datasets, and the persistence layer for query caches and local-first sync engines. For relational queries in the browser, SQLite compiled to WebAssembly on top of OPFS (chapter 12) is increasingly common.
Cache Storage
Cache Storage (caches) stores Request → Response pairs. It's designed for service workers but available to pages too:
const cache = await caches.open("static-v3");
await cache.addAll(["/", "/app.js", "/app.css", "/offline.html"]); // fetch and store
const cached = await cache.match("/app.js");
await caches.delete("static-v2"); // versioned cleanup on activate
It's separate from the browser's HTTP cache (chapter 19). You control it completely, with no automatic expiry, which is why a service worker's caching strategies (chapter 29) must manage versions and cleanup.
Concurrency and real-time APIs
Web Workers
A Web Worker runs JavaScript on a separate OS thread with its own event loop and global scope (self), and no DOM access. Communication goes through message passing (postMessage with structured clone, or transferring ownership, chapter 15). That's the CSP and actor model from Vol. 1 ch. 2, not shared-memory threads.
// main.js
const worker = new Worker(new URL("./worker.js", import.meta.url), { type: "module" });
worker.postMessage({ type: "parse", csv: hugeText });
worker.onmessage = (e) => renderTable(e.data.rows);
worker.onerror = (e) => console.error(e.message);
// worker.js
self.onmessage = (e) => {
if (e.data.type === "parse") {
const rows = parseCsv(e.data.csv); // 2 seconds of CPU work, off the main thread
self.postMessage({ rows });
}
};
Worker kinds:
| Kind | Scope | Use |
|---|---|---|
| Dedicated Worker | One page | CPU-heavy work: parsing, compression, image processing, search indexing, Wasm computation |
| Shared Worker | All same-origin tabs | One shared connection or state across tabs (not on Android Chrome) |
| Service Worker | Origin + scope; runs without a page | Network proxy, offline, push, background sync (chapter 29) |
| Worklets (Audio, Paint, Animation) | Specialised rendering and audio threads | Low-latency audio processing, CSS paint |
Libraries like Comlink make workers feel like async function calls. SharedArrayBuffer plus Atomics gives shared memory with locks and waits (Vol. 1 ch. 8 concepts), but requires cross-origin isolation (COOP + COEP headers, chapter 28). Compared with Java threads or goroutines, workers are heavier (each has its own JS heap and startup cost, so pool them for repeated work) and safer (no shared mutable state by default, so no data races).
Service Workers
A service worker is a special worker that sits between your pages and the network for its scope. It intercepts every fetch and can answer from cache, go to the network, or synthesise a response. It has a lifecycle of its own (install → activate → idle/terminated → woken by events) and keeps working when no page is open, for push messages and background sync. Chapter 29 covers it in depth with caching strategies and offline-first design. For now, the key facts: it requires HTTPS, it's event-driven (the browser kills it when idle, so you can't keep state in globals), and a buggy one can break your site for returning users until it updates. Always ship a way to unregister it.
WebSocket
WebSocket gives a persistent, full-duplex message channel over one TCP connection. It starts as an HTTP/1.1 Upgrade handshake and then switches to a lightweight framed protocol (ws:// or wss://, the latter over TLS):
function connect() {
const ws = new WebSocket("wss://api.example.com/live");
ws.binaryType = "arraybuffer";
ws.onopen = () => ws.send(JSON.stringify({ type: "subscribe", channel: "orders" }));
ws.onmessage = (e) => handle(JSON.parse(e.data));
ws.onclose = (e) => {
if (!e.wasClean) setTimeout(connect, backoffWithJitter()); // reconnect: WebSocket does NOT do it for you
};
ws.onerror = () => ws.close();
return ws;
}
What you must build yourself: reconnection with backoff and jitter, heartbeats (application ping/pong to detect dead connections and keep NATs and load balancers from timing out, Vol. 1 ch. 9), resubscription and missed-message recovery after a reconnect (sequence numbers or last-event IDs), backpressure (check ws.bufferedAmount, since the API has no flow control), authentication (browsers can't set custom headers on the WebSocket handshake, so use cookies, or a short-lived token in the first message or the URL), and horizontal scaling (sticky sessions or a pub/sub fan-out tier such as Redis or NATS, Vol. 5).
The WebSocketStream API (Chromium) adds promise-based streams with backpressure. Backend counterparts: Spring WebSocket/STOMP, Go's gorilla/websocket or coder/websocket, Rust's tokio-tungstenite and axum's WebSocket support.
Server-Sent Events
SSE (EventSource) is a one-way server-to-client stream over plain HTTP. The server holds a response open and writes text/event-stream lines:
HTTP/1.1 200 OK
Content-Type: text/event-stream
Cache-Control: no-cache
id: 42
event: order-updated
data: {"id":"o_1","status":"shipped"}
: comment lines keep the connection alive
retry: 5000
const es = new EventSource("/api/orders/stream", { withCredentials: true });
es.addEventListener("order-updated", (e) => update(JSON.parse(e.data)));
es.onerror = () => { /* the browser reconnects automatically, sending Last-Event-ID */ };
SSE's advantages: automatic reconnection with Last-Event-ID resume built in, it's plain HTTP (works through proxies, uses normal auth cookies, multiplexes over HTTP/2), and it's simple on the server (Spring's SseEmitter or WebFlux Flux<ServerSentEvent>, Go's http.Flusher). Limits: it's server-to-client only (send client messages with normal fetch), the payload is text, and on HTTP/1.1 browsers allow only 6 connections per domain, so several tabs can exhaust them. Use HTTP/2.
Choosing (chapter 19 expands this): use SSE for notifications, live feeds and LLM token streaming. Many AI APIs stream with SSE-formatted responses, but over fetch with POST, because EventSource only supports GET. Use WebSocket for chat, collaborative editing, multiplayer and anything high-frequency in both directions.
BroadcastChannel
BroadcastChannel sends messages to every same-origin browsing context (tabs, iframes, workers) that has opened a channel with the same name:
const bc = new BroadcastChannel("auth");
logoutButton.onclick = () => { logout(); bc.postMessage({ type: "logout" }); };
bc.onmessage = (e) => { if (e.data.type === "logout") location.assign("/login"); }; // log out every tab
Uses: syncing auth state, theme and cart contents across tabs, and invalidating caches. For mutual exclusion across tabs (only one tab should hold the WebSocket or run a sync), use the Web Locks API: navigator.locks.request("sync", async () => {…}).
Notifications
The Notifications API shows OS-level notifications. It needs permission, which should only be requested in response to a user action that explains why:
enableAlertsButton.addEventListener("click", async () => {
const permission = await Notification.requestPermission(); // "granted" | "denied" | "default"
if (permission === "granted") new Notification("Order shipped", { body: "#1042 is on its way", icon: "/icon.png" });
});
Notifications shown from a page work only while it's open. Push notifications, delivered when the site is closed, combine the Push API and a service worker (chapter 29), including on iOS for home-screen web apps. Don't prompt for permission on page load: users deny it, and browsers increasingly show "quiet" prompts or block sites that ask too eagerly.
Files
File, Blob and reading files
A Blob is immutable raw data with a MIME type. A File is a Blob with a name and modification date. You get Files from <input type="file">, drag-and-drop (e.dataTransfer.files), and paste events (clipboardData.files).
dropZone.addEventListener("dragover", (e) => e.preventDefault()); // required to allow dropping
dropZone.addEventListener("drop", async (e) => {
e.preventDefault();
for (const file of e.dataTransfer.files) {
file.name; file.size; file.type; // type is from the extension: don't trust it for security
const text = await file.text(); // or .arrayBuffer(), .stream(), .slice(start, end)
const url = URL.createObjectURL(file); // blob: URL for previews: img.src = url
img.onload = () => URL.revokeObjectURL(url); // release memory
}
});
// Create files in the browser and offer them for download
const blob = new Blob([JSON.stringify(data, null, 2)], { type: "application/json" });
const a = Object.assign(document.createElement("a"), { href: URL.createObjectURL(blob), download: "export.json" });
a.click();
URL.revokeObjectURL(a.href);
For large files, process them as streams (file.stream()) or in slices, rather than loading gigabytes into memory, and do the heavy work in a worker. For resumable uploads, slice the file into chunks and upload each with retries (chapter 13).
File System Access and OPFS
- The File System Access API (
showOpenFilePicker,showSaveFilePicker,showDirectoryPicker, Chromium only) gives read and write handles to real user files and folders, after the user picks them. It's what lets web IDEs (VS Code for the Web), editors and design tools save in place. - The Origin Private File System (
navigator.storage.getDirectory(), all engines) is a private, sandboxed file system per origin, invisible to the user, with fast synchronous access handles inside workers. It's the storage layer for SQLite-Wasm and for large caches.
// OPFS in a worker: fast synchronous I/O
const root = await navigator.storage.getDirectory();
const fh = await root.getFileHandle("data.bin", { create: true });
const access = await fh.createSyncAccessHandle(); // workers only
access.write(new Uint8Array([1, 2, 3]), { at: 0 });
access.flush();
access.close();
Lab: the DOM's costs and timing, measured
All experiments ran in Chromium 153 (headless, 1000 × 700 window) through Playwright. Times are medians of five runs where noted; they'll differ on your machine, but the ratios hold.
Experiment 1: four ways to add 10,000 rows
Each method builds a <ul> of 10,000 <li>Item n</li> (after clearing the previous 10,000), then reads offsetHeight to force the layout that the browser would otherwise do before the next paint:
"append one by one": for (…) { const li = document.createElement("li"); li.textContent = "Item " + i; l.append(li); }
"DocumentFragment": build all the li's in a fragment, then l.append(fragment)
"innerHTML string": build one HTML string, then l.innerHTML = s
"replaceChildren(...)": build an array of li's, then l.replaceChildren(...array)
append one by one 181.3 ms
DocumentFragment 177.8 ms
innerHTML string 153.6 ms
replaceChildren(...) 121.6 ms
The differences are much smaller than folklore suggests. Appending one at a time is not 10,000 layouts: the DOM changes are cheap, and the browser lays out once, when something needs geometry or the next frame is painted. Most of each number is the style and layout of 10,000 boxes, which no insertion trick avoids. The real lessons: don't render 10,000 rows at all (virtualise: render only what's visible, chapter 27), and never use innerHTML with untrusted data however fast it is (experiment 5). replaceChildren won here because it clears and inserts in a single operation.
Experiment 2: layout thrashing
500 boxes; for each, read its width (offsetWidth) and set it one pixel wider. First interleaved (read, write, read, write…), then batched (all reads, then all writes):
for (const d of boxes) { const w = d.offsetWidth; d.style.width = (w + 1) + "px"; } // interleaved
const ws = boxes.map(d => d.offsetWidth); // batched: reads…
boxes.forEach((d, i) => d.style.width = (ws[i] + 1) + "px"); // …then writes
interleaved 54.9 ms
batched 1.9 ms
Same work, about 30× slower interleaved. Each write invalidates layout; each subsequent read of geometry (offsetWidth, getBoundingClientRect(), scrollTop, getComputedStyle) forces the browser to recompute layout synchronously before it can answer. This forced synchronous layout, repeated in a loop, is called layout thrashing, and DevTools' Performance panel flags it with purple "Layout" blocks and a "Forced reflow" warning. Batch reads before writes, or move reads into requestAnimationFrame and writes after them (libraries like fastdom formalise this).
Experiment 3: the event path
Capture and bubble listeners on three nested elements, then a click on the innermost button:
outer capture (phase 1)
inner capture (phase 1)
btn capture (phase 2)
btn bubble (phase 2)
inner bubble (phase 3)
outer bubble (phase 3)
with stopPropagation() at inner (bubble): outer capture, inner capture, btn capture, btn bubble, inner bubble
Every DOM event travels in three phases: capture from the window down to the target's parent (eventPhase 1), at the target (2; capture and bubble listeners on the target itself both run here, in registration order), then bubble back up (3). addEventListener(type, fn, true) (or { capture: true }) listens in the capture phase. stopPropagation() stopped the event reaching outer's bubble listener; it doesn't cancel the default action (that's preventDefault()). Some events don't bubble (focus, blur, mouseenter; use focusin/focusout for delegation), and events crossing a shadow DOM boundary are retargeted so outside listeners see the host element (chapter 21).
Experiment 4: when observers fire
new MutationObserver(recs => calls.push(recs.length)).observe(m, { childList: true });
for (let i = 0; i < 100; i++) m.append(document.createElement("li"));
calls.push("sync code done");
[ 'sync code done', 100 ]
The observer didn't run 100 times during the loop. It ran once, as a microtask after the synchronous code finished, with all 100 records batched. (Its predecessor, mutation events, fired synchronously on every change and made the DOM slow; Chrome removed them in 2024.) Similarly, IntersectionObserver and ResizeObserver deliver batched entries asynchronously, tied to rendering. With 200 rows of 100 px in a 700 px window:
IntersectionObserver: visibleAtStart: 7, afterScrollingTo3000px: 15
Seven rows intersected the viewport at load (rows 0–6), and scrolling to 3,000 px reported the eight newly visible rows, with no scroll listener and no geometry reads on the main thread. That's how lazy images, infinite lists and "mark as read" features should be built.
Experiment 5: textContent versus innerHTML with hostile input
const input = '<img src="x" onerror="window.ran++">';
a.textContent = input;
b.innerHTML = input;
{ textContentImgs: 0, innerHTMLImgs: 1, onerrorRan: 1 }
innerHTML created a real <img>; its source failed to load; its onerror attribute ran attacker-controlled JavaScript in your origin, with access to the page, its cookies (unless HttpOnly) and its storage. Note that <script> tags inserted via innerHTML don't execute, which gives people false confidence; event-handler attributes do. The defences, in order: use textContent and DOM methods; if you must insert HTML, sanitise it (DOMPurify, or the new setHTML() Sanitizer API as browsers ship it); and enforce it with Trusted Types and CSP (chapter 28), which make innerHTML = string throw unless the string came through a sanitising policy.
Try it yourself
- Record experiment 2 in the DevTools Performance panel. Find the "Forced reflow" warnings and the line of code they point to.
- Rewrite the shopping list so the data lives in an array of
{ id, text, done }objects and a singlerender()function rebuilds the list from it. Which bugs became impossible? What got slower? - Add 10,000 items to the shopping list. Then implement a simple virtual list: render only the visible items plus a few above and below, inside a tall spacer element.
- Make the list's state survive a reload with
localStorage, and sync it across two open tabs with thestorageevent orBroadcastChannel.
Revision sheet: the DOM and browser APIs
Key ideas
- The DOM is a tree of
Nodes (elements, text, comments) under aDocument; query with CSS selectors (querySelector,closest,matches); liveHTMLCollections vs staticNodeLists. - Change content with
textContent, properties,classList,dataset,append/replaceChildren; build withcreateElement,<template>cloning or fragments;innerHTMLonly for trusted or sanitised HTML. - Events: capture → target → bubble;
preventDefaultvsstopPropagation; passive listeners for scroll and touch;AbortSignalto remove many listeners at once ({ signal }); delegation withclosest(). - Rendering cost: DOM writes are cheap until something reads geometry; interleaving reads and writes forces synchronous layout (thrashing); batch reads, then writes.
- Observers:
MutationObserver(microtask, batched),IntersectionObserverandResizeObserver(async, tied to rendering),PerformanceObserver(performance entries). - Networking APIs:
fetchwith streams andAbortSignal;WebSocketfor bidirectional messages;EventSource(SSE) for server push over HTTP;BroadcastChannelbetween same-origin tabs. - Storage and files: IndexedDB, Cache Storage, OPFS;
File/Blob/URL.createObjectURL; the File System Access API (Chromium) for real files. - Other APIs: Clipboard (async, permission-gated), Web Crypto (
subtlein secure contexts,randomUUID), Notifications and Push (via service workers), the History and Navigation APIs.
Numbers to remember
- Forced layouts in a loop: about 30× slower than batched in this chapter's lab (500 boxes: 55 ms vs 2 ms).
- A frame at 60 Hz: 16.7 ms; DOM work per frame should leave room for style, layout and paint.
- Practical DOM size: Lighthouse warns above about 1,400 elements; thousands of rows need virtualisation.
Pitfalls
innerHTML,outerHTML,insertAdjacentHTMLanddocument.writewith untrusted strings (XSS).- Listeners added in loops and never removed (leaks in single-page apps); anonymous listeners that can't be removed (use
AbortController). - Listening to
clickon submit buttons instead ofsubmiton forms; forgettingtype="button". - Reading layout in scroll handlers instead of using
IntersectionObserver. - Querying the DOM for application state instead of keeping state in data structures.
- Using
keypress(deprecated) orkeyCodeinstead ofkeydownandevent.key.
Glossary
- Event delegation: handling events from many children with one listener on an ancestor.
- Default action: what the browser does after dispatch unless prevented (follow a link, submit a form, scroll).
- Forced synchronous layout: layout computed immediately because script read geometry after a change.
- Live collection: a collection that updates as the DOM changes (
getElementsByTagName,children). - Retargeting: events from inside a shadow tree appearing to come from its host element.
- Trusted Types: a browser mechanism that blocks string assignments to dangerous DOM sinks unless they come from an approved policy.