Workbench / Volume 2 Exercises: The Web Frontend
V2·17
DOM and Browser APIs
Exercises for Volume 2, chapter 17: traversal and querying (static vs live collections, closest and matches), creating and changing the DOM (textContent, innerText, innerHTML, fragments, batching reads and writes), events, propagation, delegation, CustomEvent and listener options; MutationObserver, IntersectionObserver, ResizeObserver and PerformanceObserver; Fetch, URL, History and the Navigation API, Clipboard and Web Crypto; IndexedDB and Cache Storage; Web Workers, Service Workers, WebSocket, Server-Sent Events, BroadcastChannel and Notifications; and files (File, Blob, object URLs, File System Access and OPFS). 10 theory questions, 10 programming exercises, 3 cumulative projects, the concepts the chapter leaves out, and 5 senior-level exercises.
Start here: how this chapter's exercises work
Same four sets and the same locking. Every API here runs in the browser, so the exercises are small pages you open from a local server (python3 -m http.server): localhost counts as a secure context, which several APIs require (Web Crypto's subtle, service workers, the Clipboard API, OPFS). The outputs in the solutions come from Chromium 153 via Playwright, against a small Python server that also served the Server-Sent Events stream in P9.
The chapter's own lab already measured DOM insertion methods, layout thrashing, event phases and innerHTML XSS; these exercises build on those and cover the rest of the toolbox.
Coverage map.
| Chapter component | Exercises |
|---|---|
| traversal and querying: static vs live collections, closest, matches | T1, P1 |
| creating and changing the DOM; textContent vs innerText vs innerHTML; batching | T2, P1 |
| events, propagation, delegation, listener options, CustomEvent | T3, P2 |
| MutationObserver, IntersectionObserver, ResizeObserver, PerformanceObserver | T4, P3 |
| Fetch, URL, History and Navigation API | T5, P4 |
| Clipboard and Web Crypto | T6, P5 |
| IndexedDB and Cache Storage | T7, P6 |
| Web Workers and Service Workers | T8, P7 |
| WebSocket, Server-Sent Events, BroadcastChannel, Notifications | T9, P8, P9 |
| File, Blob, object URLs, File System Access, OPFS | T10, P10 |
Theory
T1. Finding elements
- P1 removed a class from every element of
document.getElementsByClassName('d')in aforloop and two of four elements kept the class; doing the same overquerySelectorAll('.d')removed it from all. Explain live versus static collections. - When do you use
getElementById,querySelector(All),closest,matches,childrenvschildNodes, andelement.querySelectorscoped to a component? Why should JavaScript select bydata-*attributes or roles rather than by styling classes? - In a page with 5,000 dish cards, what's the cost of
document.querySelectorAll('*')-style broad queries in a loop, and how do you avoid repeated queries?
T2. Changing the DOM safely and efficiently
- P1 put
<p>Visible <span style="display:none">HIDDEN</span> text</p><style>p{}</style>in a box:textContentwas"Visible HIDDEN textp{}"andinnerTextwas"Visible text". Explain the difference, including the cost ofinnerText. - The chapter's lab measured inserting 10,000 elements: one by one 181 ms,
DocumentFragment178 ms, aninnerHTMLstring 154 ms,replaceChildren(...)122 ms; and layout thrashing (interleaved reads and writes) 55 ms versus 1.9 ms batched. What do these numbers say about where the real cost is? - List the safe and unsafe ways to put user-provided text into a page (
textContent,createElement+setAttribute, template elements,innerHTML,insertAdjacentHTML,outerHTML,setHTMLwith the Sanitizer API) and which are XSS sinks.
T3. Events
- Describe the three propagation phases (capture, target, bubble). What's the difference between
event.targetandevent.currentTarget? P2's delegated click on a<span>inside a<button data-id="7">inside a<ul>listener gave targetSPAN, currentTargetUL, andclosest('button').dataset.id="7". - Compare
stopPropagation,stopImmediatePropagationandpreventDefault, with an example where each is right and one wherestopPropagationcauses a bug (analytics, dropdown "click outside" handlers). - P2:
focusdidn't reach a listener onbodybutfocusindid; a{passive: true}wheel listener'spreventDefault()had no effect (defaultPreventedfalse);{once: true}ran once for two dispatches; aCustomEventreacheddocumentonly withbubbles: true. Explain each option and when you'd use it. - Why is event delegation useful for lists that change (5,000 dishes, infinite scroll), and what are its pitfalls?
T4. Observers
- The chapter's lab showed a
MutationObserverfiring once after 100 synchronous changes, as a microtask with 100 records batched. Why is that design better than the old synchronous mutation events, and what do you use MutationObservers for (and not for)? - Explain IntersectionObserver's
root,rootMarginandthreshold, and give three uses: lazy-loading images in browsers withoutloading="lazy", infinite scroll, analytics "was this dish card seen?". Why is it better than ascrolllistener withgetBoundingClientRect? - P3's ResizeObserver reported a box's width as 300 then 500 after a style change. When do you need ResizeObserver rather than container queries (chapter 14)?
- What does PerformanceObserver observe (LCP, layout shifts, long tasks, long animation frames, resource timing, event timing), and why use
buffered: true?
T5. Fetch, URLs and navigation APIs
- What does
fetchdo and not do: it resolves on HTTP errors (checkres.ok), doesn't time out by default, sends cookies only for same-origin by default (credentials), and its body can be read once. How doRequest,Response,Headersand streaming bodies fit together? - Compare
history.pushState/popstatewith the Navigation API (navigation.navigate, thenavigateevent withintercept()), for an SPA's routing: scroll restoration, focus, cancellation and Back/Forward handling. - Why must a client-side router also update the document title, move focus and announce the page change for screen readers?
T6. Clipboard and Web Crypto
- What does the async Clipboard API require (secure context, user activation, permissions for reading), and how do you implement "Copy coupon code" robustly?
- P5 used Web Crypto to compute SHA-256 of
order_42|22900(e5898801a5ad4a9e…), signed it with HMAC and verified (true) and a tampered message (false), and generated a v4 UUID. What arecrypto.getRandomValues,crypto.randomUUIDandcrypto.subtlefor, and why isMath.random()wrong for IDs and tokens? - P5's HMAC key was generated in the browser. Why can't a browser keep a secret from its user, and what does that mean for "signing" API requests or "encrypting" data client-side?
T7. IndexedDB and Cache Storage
- P6 started a
readwritetransaction,puta record, thenawait fetch(...), then tried anotherput: it failed withTransactionInactiveError: … The transaction has finished., and only one record was stored. Explain IndexedDB's auto-committing transactions and the rule this implies. - Design an IndexedDB schema for TiffinBox's offline menu and order history: object stores, keys, indexes, versioned upgrades (
onupgradeneeded), and what happens when two tabs have different versions of the app open (onversionchange,blocked). - Compare the Cache API with IndexedDB: what each stores, who usually uses it (service workers), and their eviction and quota behaviour (chapter 12's T10).
T8. Workers and service workers
- Compare dedicated workers, shared workers and service workers: lifetime, scope, what they can access, and a TiffinBox use for each.
- Describe the service worker lifecycle (register, install, waiting, activate, fetch, terminate), and the update problem: why does a new version "wait", and how do
skipWaiting,clients.claimand an "Update available, reload" prompt fit together safely? - Write the caching strategy for: the app shell (HTML, CSS, JS), dish images, the menu API, and the "place order" POST. Name the strategies (cache-first, network-first, stale-while-revalidate, network-only).
- What can go badly wrong with service workers (serving stale HTML forever, caching error responses, caching personal data on shared devices), and how do you have a kill switch?
T9. Real-time: WebSocket, SSE, BroadcastChannel, Notifications
- Compare polling, long polling, Server-Sent Events and WebSockets for (a) order status updates, (b) live delivery-partner location every 2 s, (c) a two-way support chat. P9's SSE stream sent
retry: 300, three events withid:s, closed, and the browser reconnected after ~300 ms withLast-Event-ID: 3and received events 4–6. Explain how SSE resumption works. - What must a WebSocket client handle that SSE does for you (reconnection, back-off, heartbeats, message framing and ordering, authentication, resubscription), and what server-side issues appear at scale (load balancers, idle timeouts, sticky sessions)?
- P8 sent a
BroadcastChannel('cart')message from one tab and another tab received it. Give two uses (cart sync, logout everywhere) and the alternative (storageevents). - What do the Notifications and Push APIs require, and why is asking for notification permission on page load a mistake?
T10. Files
- Compare
File/Blob,FileReader,blob.text()/arrayBuffer()/stream(), and object URLs. P10 created a Blob URL for a CSV, fetched it (17 bytes), revoked it, and a second fetch failed withTypeError: Failed to fetch. Why must you revoke object URLs, and when? - What do the File System Access API (
showOpenFilePicker,showSaveFilePicker) and the origin private file system (OPFS: P10 wrote and readmenu-cache.jsonvianavigator.storage.getDirectory()) offer, and how do their availability and security models differ? - Design "download my order history as CSV" without a server round trip, and "upload a dish photo with a preview and size check" (chapter 13's P11), using this chapter's APIs.
Programming exercises
P1. Querying and changing the DOM
On a page with four <li class="d"> items: remove the class in a for loop over getElementsByClassName('d') and count what's left; repeat with querySelectorAll. Then build a delegated click handler on a <ul> for <button data-id> elements with nested <span>s, printing target, currentTarget and the closest('button') id. Then compare textContent and innerText on a box with a hidden span and a <style> element.
P2. Events and listener options
Write listeners that show: focus vs focusin reaching document.body; a passive wheel listener calling preventDefault() (check defaultPrevented); {once: true} with two dispatches; a CustomEvent('cart:added', {detail, bubbles: true}) heard on document, and the same without bubbles. Then build a dropdown that closes on "click outside" using a document-level listener, and show how a child's stopPropagation() breaks it; fix it without stopPropagation.
P3. Observers at work
Build: (a) a MutationObserver on a list, then append 100 items synchronously and count callbacks and records; (b) an IntersectionObserver with rootMargin: '200px' that lazy-loads images and an infinite-scroll sentinel that loads the next page of dishes; (c) a ResizeObserver on a chart container that redraws a canvas at its new width (P3 measured 300 then 500); (d) a PerformanceObserver with buffered: true logging LCP and layout shifts.
P4. Client-side routing with history and the Navigation API
Build a two-view mini-app (menu list and dish detail) with client-side routing: first with history.pushState + popstate + intercepted link clicks, then with the Navigation API's navigate event and intercept(). In both, set document.title, move focus to the new view's <h1>, restore scroll on Back, and cancel a slow data load when the user navigates again. Test Back/Forward, opening a dish link in a new tab, and a direct visit to /dishes/42 (the server must serve the app for that URL).
P5. Copy, hash, sign and random
Implement a "Copy coupon" button with navigator.clipboard.writeText, live-region feedback and a manual fallback. Then with Web Crypto: compute the SHA-256 of order_42|22900 as hex; generate an HMAC key, sign and verify the message and a tampered one; generate a UUID and 16 random bytes as base64url. Finally, measure how quickly you can predict Math.random(): research (don't implement) why V8's xorshift128+ is predictable, and list where your codebase uses Math.random() for anything security-relevant.
P6. IndexedDB done right
Create a tiffinbox database with orders (keyPath id, indexes byKitchen and byCreatedAt) and outbox stores. Reproduce P6's bug: in a readwrite transaction, put one order, await fetch(...), then put another; read the error and count stored records. Fix it by fetching first. Then add a version 2 migration that adds an index, open the app in two tabs with different versions, and handle versionchange and blocked.
P7. A service worker with a safe update flow
Write sw.js that pre-caches the app shell on install, serves hashed assets cache-first, the HTML network-first with a cached fallback, the menu API stale-while-revalidate, and never caches POSTs or authenticated responses. Register it, go offline in DevTools (Application → Service Workers → Offline) and reload. Then change sw.js, observe the new worker "waiting", and implement the "Update available → Reload" flow with skipWaiting on request. Finally, write the kill-switch sw.js.
P8. Cross-tab sync and notifications in context
Open two tabs of the same page. In tab A, post a BroadcastChannel('cart') message when an item is added; in tab B, update the cart badge on receipt. Then implement "log out everywhere" (tab A logs out; all tabs clear state and redirect) with BroadcastChannel and, as a fallback, the storage event. Finally, add an in-context "Notify me when my order is out for delivery" button that asks for notification permission only on click, and show a local notification from the page (or service worker) for testing.
P9. Server-Sent Events with resumption
Write a small server (Python or Java) with /events that sends retry: 300, three order events with increasing id:s, and then closes the connection; on the next request it reads Last-Event-ID and continues from there. Consume it with EventSource, log events and errors with timestamps, and check the server log for the reconnect. Then add a heartbeat comment line (: ping) every 15 s, and discuss what happens through a proxy that buffers responses.
P10. Files, Blob URLs and OPFS
(a) Create a CSV Blob, make an object URL, fetch it, revoke it and fetch again (P10: 17 bytes, then TypeError: Failed to fetch). (b) Implement "Download order history as CSV" with proper escaping, a UTF-8 BOM and protection against CSV injection; open the file in Excel or LibreOffice with Hindi and Telugu names. (c) Write and read a JSON file in OPFS. (d) Build a photo upload with preview, magic-byte check and a downscale to 1,600 px in a worker using createImageBitmap and OffscreenCanvas.
Cumulative projects (chapters so far: Volume 1, and Volume 2's 00, 12–17)
C1. A vanilla-JS, offline-capable order tracker
Without a framework, build an order-tracking page: it loads the order (chapter 15's API client with chapter 16's schema validation), subscribes to status updates via SSE with resumption, shows a live progress timeline (accessible: status changes announced in a live region), stores the last known state in IndexedDB so reopening the page offline shows it with "Last updated" time, syncs across tabs with BroadcastChannel (one SSE connection shared: the "leader" tab holds it, using the Web Locks API to elect a leader), works with a service worker for the shell, and offers in-context notification permission.
Combines: reconnection and back-off (Vol 1 ch 09); leader election as mutual exclusion (ch 08); state machines (ch 05, 16's P4); TypeScript types and schemas (ch 16); JavaScript async (ch 15); this chapter's SSE, IndexedDB, BroadcastChannel, service workers and notifications.
C2. A dish image pipeline in the browser
Let kitchen partners upload up to 20 dish photos at once: drag and drop or file picker, previews (object URLs, revoked properly), validation (type by magic bytes, size, minimum resolution), downscaling and WebP conversion in a worker pool sized to navigator.hardwareConcurrency, SHA-256 hashing to skip duplicates already uploaded, upload with concurrency 3, per-file progress, retry for failed uploads with idempotency keys, and cancellation. Report the total bytes saved by downscaling.
Combines: worker pools and concurrency limits (Vol 1 ch 08, 11's thread pool); hashing and deduplication (ch 03, 05); binary formats and magic bytes (ch 06); retries and idempotency (ch 09); this volume's JavaScript async (ch 15) and this chapter's files, workers, Web Crypto and fetch.
C3. Measure and fix a janky dish list
Build (or take) a page that renders 5,000 dish cards with images, filters and a "favourite" toggle, and make it slow on purpose: per-card listeners, layout reads in loops, innerText reads, a scroll listener calculating visibility, and re-rendering everything on each filter change. Measure INP for the favourite toggle and filter typing, and scrolling smoothness, with the Performance panel at 6× CPU throttling and with a PerformanceObserver for event and long-animation-frame entries. Then fix it step by step (delegation, batched reads and writes, textContent, IntersectionObserver, content-visibility: auto, incremental rendering) and record each step's effect.
Combines: algorithmic cost of repeated queries (Vol 1 ch 04); caches and layout (ch 07); this volume's event loop (ch 12, 15), CSS rendering costs (ch 14) and this chapter's DOM, events and observers.
What the chapter leaves out
Shadow DOM and web components in practice
Custom elements (chapter 13's gaps) usually use shadow DOM for encapsulation: styles inside don't leak out and page styles don't leak in (except inherited properties and custom properties, which is how theming works), <slot>s project light-DOM children, and events are retargeted at the shadow boundary (event.target appears as the host from outside; use event.composedPath() to see the real path, and composed: true for custom events that should cross). Gotchas: document.querySelector can't see inside shadow roots (tests need piercing selectors: Playwright pierces open shadow roots by default), forms need ElementInternals, and accessibility relationships (aria-labelledby) across shadow boundaries are limited. Useful for design systems shared across frameworks.
Permissions, feature policy and capability detection
Many APIs in this chapter are gated: secure contexts, user activation, permission prompts (navigator.permissions.query({name: 'notifications'}) reads the state without prompting), and Permissions Policy for iframes (chapter 12's gaps). Always feature-detect ('serviceWorker' in navigator, typeof navigation !== 'undefined', 'showOpenFilePicker' in window) and design a fallback path; check the user's actual browser mix (Android WebViews, Safari on iOS, where every browser uses WebKit) before building on newer APIs like the Navigation API, File System Access or Web Bluetooth.
Device and media APIs
Beyond this chapter: geolocation (watchPosition for delivery partners; battery and permission costs; never required for browsing a menu), media capture (getUserMedia for scanning QR codes or video support calls), Web Share (navigator.share to share a dish via WhatsApp: very effective on mobile), Payment Request API (native payment sheets; in India, UPI intent flows are more common), WebAuthn/passkeys (phishing-resistant login: Volume 3's security chapter), Screen Wake Lock (keep the screen on for a kitchen display), and Vibration, Battery and sensor APIs (limited or removed in several browsers for privacy). Each needs feature detection, permission UX and privacy review.
Testing browser APIs
Code using these APIs needs tests that control them: Playwright can grant permissions (context.grant_permissions(['notifications'])), emulate offline (set_offline), geolocation and time zones, intercept network requests (page.route) to simulate slow or failing APIs, and run multiple pages for cross-tab behaviour (as P8 and P9 did). Unit tests in jsdom or happy-dom lack layout, IntersectionObserver and real storage semantics, so use them for logic and run behaviour that depends on the browser in real browsers (chapter 26).
Web performance APIs beyond observers
performance.mark()/measure() for custom timings ("menu rendered"), the User Timing marks showing up in the Performance panel, Server-Timing headers surfaced in resource timing (the backend reports DB time per request, visible in DevTools and RUM), navigator.connection (effective connection type, saveData for data-saver users: send smaller images), and the Reporting API for CSP violations, deprecations and crashes (Reporting-Endpoints header). They connect this chapter's APIs to chapters 27 and 32.
Senior exercises
S1. Diagnose "the app shows yesterday's menu"
After a release, some users see stale menus (yesterday's dishes, old prices) and some still run last week's JavaScript, even after reloading. The app uses a service worker built a year ago, IndexedDB caching and an HTTP cache. Lay out the investigation (which caches can be stale, how to inspect each in DevTools and in the field), the likely causes, the immediate mitigation, and the long-term fix.
S2. Choose a real-time architecture for order tracking at scale
TiffinBox expects 200,000 concurrent users watching order status during dinner peaks, plus 20,000 delivery partners sending GPS every 5 s. Choose between polling, SSE and WebSockets for each side, design the server architecture (connection servers, pub/sub, state store), reconnection behaviour, load-balancer and timeout settings, and estimate resources. Explain what happens during a deploy and during a partial outage.
S3. Review a pull request that uses many browser APIs
A PR adds a "kitchen display" page: it requests notification and geolocation permission on load, polls /api/orders every second with setInterval (never cleared), stores the auth token and all orders in localStorage, plays a sound with new Audio() on each new order, keeps the screen awake with a hidden looping video, and renders orders by setting innerHTML from the API data. Write the review, ranked by severity.
S4. Decide what the frontend should do offline
Product wants "TiffinBox works offline". Define what that should mean for each feature (browsing menus, the cart, placing orders, order tracking, account settings, the kitchen display), the data that must be cached, conflicts and their resolution, what the UI must show, the security and privacy constraints, and how you'd test it. Push back where "offline" doesn't make sense.
S5. Teach event delegation and observers instead of scroll listeners
Write a 10-minute talk for frontend engineers who reach for scroll listeners and per-element click handlers by habit. Include two before/after code snippets, a measurement they can reproduce, and three rules.