Specialization DepthVol. 17 · Part XVII
0 / 0

Trails / Specialization Depth

SD·195A

Frontend Depth I: HTML, CSS, JavaScript, TypeScript, the Browser and Accessibility

The foundations of the frontend track at L5/L6, with experiments run in Node and Chromium: level ladders; HTML as semantics and contract; CSS at L3 (cascade, specificity, layout algorithms, containing blocks, stacking contexts) and at L5 (architecture, design tokens, container queries); JavaScript's execution model — the event loop's exact ordering of sync code, microtasks and macrotasks — plus closures, prototypes and memory; TypeScript's deliberate unsoundness (three programs that pass --strict and fail at runtime) and how to design types and runtime validation around it; browser internals from bytes to pixels, with layout thrashing measured (490 ms interleaved versus 2.5 ms batched for 1,000 rows); and accessibility from first principles — the accessibility tree, WCAG 2.2, an axe-core audit finding seven violations, and the keyboard bug it cannot see.

16 topics · ~18 min read · 30-question quiz
Updated Suggest a correction

Start here: what L5/L6 depth in the web platform looks like

A frontend specialist at L2 builds pages that work. At L3 they know how the browser turns bytes into pixels, how the JavaScript event loop schedules work, how CSS layout is computed and how the accessibility tree is built. At L4 they can open a performance trace and say exactly why a click felt slow. At L5/L6 they set the platform choices, budgets and practices for a whole product, and keep them as the app grows.

Two examples measured in a real browser

Layout thrashing. Updating 2,000 elements' widths in a loop that reads each element's size and then writes a new one forces the browser to recalculate layout on every read: 764–879 ms. Doing all the reads first, then all the writes, takes 6.6–7.8 ms, over 100× faster, with identical results.

A blocked main thread. JavaScript runs on the page's single main thread; while it's busy, clicks wait. With a 500 ms task running, a click was handled after ~470 ms; with the same 500 ms of work split into 50 ms chunks that yield back to the browser, after ~20 ms. Users experience the first as a frozen page. Google's INP (Interaction to Next Paint) metric measures exactly this, and "good" means under 200 ms.

These aren't framework tricks; they follow from how the browser's rendering pipeline and event loop work, which is why L3 understanding transfers across React, Angular, Vue or none.

How deep to go in the web platform

Volume 17 defines six mastery levels; for this chapter's topics they look like this:

Level You can…
L1 name HTML, CSS, JavaScript, TypeScript and browser concepts
L2 build accessible, typed, working pages and components
L3 explain the rendering pipeline, event loop, cascade and layout, type system and accessibility tree
L4 diagnose jank, layout shifts, slow interactions, type holes and accessibility failures with DevTools
L5 set platform choices, budgets and patterns for a product's front end
L6 keep a large front end fast, accessible and maintainable across teams and years

The ladders

Level HTML & CSS JavaScript & TypeScript Browser internals Accessibility
L1 Knows elements, selectors, the box model Knows syntax, types, async/await Knows that browsers parse, lay out and paint Knows a11y matters; knows WCAG exists
L2 Builds responsive layouts with flexbox/grid; semantic markup; forms Writes modern JS/TS: modules, async, generics, narrowing; uses the DOM and fetch Uses dev tools: elements, network, console Uses labels, alt text, headings; runs automated checks
L3 Explains the cascade, specificity, inheritance, layout algorithms, containing blocks, stacking contexts, formatting contexts Explains the event loop, closures, prototypes, this, garbage collection, module loading; TS structural typing, inference, variance, erasure Explains the pipeline: parse → style → layout → paint → composite; threads; what triggers layout and paint Explains the accessibility tree, roles/names/states, focus management, how screen readers and other assistive tech consume pages
L4 Diagnoses layout bugs (collapsing margins, overflow, z-index wars), specificity conflicts Diagnoses memory leaks, race conditions in async code, unhandled rejections, type holes Diagnoses jank, layout thrashing, long tasks, slow paints with the Performance panel Diagnoses with screen readers (NVDA, VoiceOver), keyboard-only use, accessibility inspector
L5 Designs CSS architecture, design tokens and themes, component styling strategy Designs type models (discriminated unions, branded types), runtime validation boundaries, module structure Designs rendering strategy for performance (what runs on the main thread, what's composited) Designs accessible components and patterns; sets an a11y process
L6 Maintains CSS at scale across teams and years; browser support policy Maintains large TS codebases: strictness migrations, tooling upgrades Owns real-user performance in production Owns conformance (audits, legal obligations), regressions, user feedback

HTML: semantics are a contract

HTML elements carry meaning that browsers, assistive technologies, search engines, browser extensions and reader modes all rely on. <button> is focusable, keyboard-activatable (Enter and Space), announced as a button, and submits forms by default; a <div onclick> is none of those. <a href> navigates and can be opened in a new tab; a <span> with a click handler can't. <label for> names an input for screen readers and enlarges its click target. <main>, <nav>, <header>, headings <h1>–<h6> create the structure assistive tech users navigate by. Native form validation, <dialog>, <details>, and the Popover API give behaviour for free that custom components must reimplement.

L5 rule: use the native element whenever one exists; reach for ARIA only to describe what HTML can't (the first rule of ARIA is "don't use ARIA if a native element will do", because ARIA changes what's announced but adds no behaviour).

CSS at L3

  • The cascade decides which declaration wins: origin and importance (user-agent, user, author; !important reverses the order), cascade layers (@layer, an explicit ordering above specificity), specificity (inline > id > class/attribute/pseudo-class > element), then source order. Many "CSS doesn't work" bugs are cascade misunderstandings.
  • Inheritance: some properties (color, font) inherit; most layout properties don't.
  • Layout algorithms: each display type has its own: flow (block and inline), flexbox (one-dimensional distribution), grid (two-dimensional tracks), positioned (absolute relative to the containing block), table, multi-column. A property's meaning depends on the algorithm (width: auto differs in flow and in flex items).
  • Containing blocks and formatting contexts: percentages, absolute positioning and margin behaviour are relative to a containing block; a new block formatting context (display: flow-root, flex/grid containers, overflow other than visible) contains floats and stops margin collapsing.
  • Stacking contexts: z-index only orders siblings within the same stacking context; properties like opacity < 1, transform, filter, position: fixed, isolation: isolate create new contexts. "z-index: 9999 doesn't work" is almost always a stacking-context problem.

L5 CSS: an architecture that scales across teams: design tokens (named values for colour, spacing, type, radius, motion; exported to CSS custom properties and to native platforms), a component styling strategy (CSS Modules, utility-first like Tailwind, or zero-runtime CSS-in-JS: choose for team and performance, not fashion), cascade layers to tame third-party CSS, container queries so components respond to their container rather than the viewport, logical properties (margin-inline-start) for right-to-left languages, and prefers-reduced-motion, prefers-color-scheme, forced-colors support.

JavaScript's execution model

JavaScript runs on a single thread per realm, driven by an event loop: run a task (macrotask: a script, a timer callback, an event, a message) to completion, then drain all microtasks (promise reactions, queueMicrotask, await continuations), then (in browsers) possibly render, then the next task. The exact ordering, run in Node:

JavaScript
// Event loop ordering: synchronous code, then ALL microtasks (promises, queueMicrotask), then the next macrotask
console.log("1 sync start");
setTimeout(() => console.log("6 timeout (macrotask)"), 0);
Promise.resolve().then(() => console.log("3 promise.then (microtask)"))
                 .then(() => console.log("5 chained then (microtask, queued by 3)"));
queueMicrotask(() => console.log("4 queueMicrotask"));
(async () => { console.log("2 async fn body runs synchronously until first await"); await null; console.log("4b after await (microtask)"); })();
console.log("2b sync end");
Text
1 sync start
2 async fn body runs synchronously until first await
2b sync end
3 promise.then (microtask)
4 queueMicrotask
4b after await (microtask)
5 chained then (microtask, queued by 3)
6 timeout (macrotask)

L3 consequences: an async function runs synchronously until its first await; microtasks run before any timer, however short; a promise chain that keeps queueing microtasks starves rendering and input (the page freezes even though you "used async"); setTimeout(fn, 0) yields to rendering and input, a microtask doesn't.

Other L3 essentials: closures capture variables (not values), which is how event handlers keep state and how they leak memory (a long-lived listener holding a closure that references a detached DOM tree); prototypes and this binding rules (arrow functions capture this lexically); garbage collection is reachability-based, so leaks are references you forgot (global caches, listeners, timers, closures); modules are evaluated once and cached, with live bindings.

TypeScript: designing around a deliberately unsound type system

TypeScript's goal is useful checking of real JavaScript, not soundness. Knowing where it's unsound is L3; designing so that it doesn't matter is L5. Three programs that compile with zero errors under --strict (TypeScript 5.9) and misbehave at runtime:

TypeScript
// TypeScript is deliberately unsound in places: these compile without errors under --strict, then fail at runtime
type Dish = { name: string };
type Priced = Dish & { price: number };

const priced: Priced[] = [{ name: "Biryani", price: 180 }];
const dishes: Dish[] = priced;                 // arrays are covariant (allowed)
dishes.push({ name: "Free sample" });          // ...so this pushes a Dish without price into a Priced[]
const total = priced.reduce((s, d) => s + d.price, 0);
console.log("total:", total);                  // NaN at runtime

const byId: Record<string, Dish> = {};
const d = byId["missing"];                     // typed as Dish without noUncheckedIndexedAccess
console.log("name length:", d?.name.length);   // without ?. this would throw

function parse(json: string): Priced { return JSON.parse(json); }   // any → Priced: no runtime check at all
console.log("price + 1:", parse('{"name":"Rajma","price":"120"}').price + 1);   // "1201"
Text
$ tsc --strict --noEmit unsound.ts      (no errors)
total: NaN
name length: undefined
price + 1: 1201

Each is a known trade-off: mutable arrays are covariant for convenience; index signatures assume presence unless you enable noUncheckedIndexedAccess; any (which JSON.parse returns) silently converts to anything. L5 design:

  • Validate at the boundaries: every value entering from outside (HTTP responses, localStorage, postMessage, URL params, JSON) is parsed with a runtime schema (zod, valibot, ArkType) that produces a typed value or an error. Inside the boundary, types can be trusted.
  • Make illegal states unrepresentable: discriminated unions ({status: "loading"} | {status: "ok", data: Menu} | {status: "error", error: string}) instead of optional fields that can contradict each other; exhaustive switch with a never check.
  • Branded types for identifiers that shouldn't mix (type SubscriptionId = number & { readonly __brand: "SubscriptionId" }).
  • readonly arrays and properties where mutation isn't intended (also fixes the covariance hole: readonly Dish[] can't be pushed to).
  • Compiler flags beyond strict: noUncheckedIndexedAccess, exactOptionalPropertyTypes, noImplicitOverride; lint rules banning any (@typescript-eslint/no-explicit-any, no-unsafe-*).
  • Generated types from the API contract (OpenAPI → TypeScript), so front end and back end can't drift (Volume 16, ch. 187).

The same "types vs runtime" question appears in every language with erasure or escape hatches: Java generics are erased (heap pollution through raw types), Python type hints aren't enforced at runtime (pydantic validates at boundaries, exactly like zod), Rust and Haskell put far fewer holes in the type system at the cost of more ceremony.

Browser internals: from bytes to pixels

The rendering pipeline for each frame:

bytes parseDOM · CSSOM style layout paint compositeGPU thread width, top, font-size color, background transform, opacity (own layer)
The browser rendering pipeline. Network bytes are parsed into the DOM and CSSOM; style resolution computes each element's styles; layout computes geometry; paint records drawing commands into layers; compositing assembles layers on the GPU, often on a separate thread. Changing geometry reruns layout and everything after it; changing only colours skips layout; changing transform or opacity on a composited layer can skip to compositing.
  • Threads: the main thread runs JavaScript, style, layout and paint recording; the compositor thread (and GPU process) assembles layers and handles scrolling and composited animations. A busy main thread can't respond to input but composited animations and scrolling can stay smooth.
  • Frame budget: at 60 Hz, 16.7 ms per frame for script + style + layout + paint; at 120 Hz, 8.3 ms. A long task (> 50 ms) blocks input handling, which is what INP measures.
  • Forced synchronous layout: reading a geometry property (offsetWidth, getBoundingClientRect(), scrollTop) after a style change forces the browser to run layout now to answer accurately. Alternating writes and reads forces a layout per iteration: layout thrashing.

Measured in Chromium (Playwright) on 1,000 rows:

JavaScript
// interleaved: read, write, read, write… (forces a layout on every read after a write)
for (const el of rows) { el.style.width = (el.offsetWidth - 1) + 'px'; }
// batched: all reads first, then all writes (one layout)
const w = rows.map(el => el.offsetWidth); rows.forEach((el, i) => el.style.width = (w[i] - 1) + 'px');
Text
1000 rows: interleaved read/write 490.5 ms, batched reads then writes 2.5 ms

Same result, 200× faster, and the slow version is a 490 ms long task that freezes the page. In the Performance panel the slow version shows hundreds of purple "Layout" blocks with "Forced reflow" warnings. Frameworks largely protect you (React batches DOM writes), but measurement code, animation libraries and third-party widgets do this all the time.

L5 rendering decisions: animate transform and opacity (compositor-only) rather than top/width; use content-visibility: auto for long off-screen content; virtualise long lists (render only visible rows); move heavy computation to Web Workers; break long tasks up (scheduler.yield() where available, or setTimeout chunking); use requestAnimationFrame for visual updates; and measure on mid-range Android devices, not a developer laptop (the 75th-percentile user in India is on a phone far slower than a MacBook).

Accessibility from first principles

Browsers build an accessibility tree alongside the DOM: for each meaningful node, a role (button, link, heading level 2, checkbox), a name (from the label, content, alt, aria-label), a state (checked, expanded, disabled, invalid) and relationships. Screen readers (NVDA, JAWS, VoiceOver, TalkBack), voice control, switch devices and braille displays consume that tree through platform accessibility APIs. If the tree is wrong, the page is wrong for those users, however it looks.

WCAG 2.2 (W3C, 2023) organises requirements under four principles (perceivable, operable, understandable, robust) at levels A, AA, AAA; AA is the usual legal and contractual target (EN 301 549 in the EU and the European Accessibility Act applying since June 2025; Section 508 in US federal procurement; India's Rights of Persons with Disabilities Act and its accessibility standards (GIGW) for government sites). WCAG 2.2 added criteria such as visible focus not being obscured, minimum target size (24×24 CSS px), accessible authentication (no cognitive tests), and alternatives to dragging.

An automated audit with axe-core in Chromium, before and after fixing a small "skip a lunch" form:

HTML
<!-- before -->
<div class="title">Skip a lunch</div>
<img src="biryani.jpg">
<input type="date" id="d" placeholder="Date">
<div class="btn" onclick="skip()" style="color:#aaa;background:#fff">Skip</div>

<!-- after -->
<html lang="en"><head><title>Skip a lunch</title></head><body><main>
<h1>Skip a lunch</h1>
<img src="biryani.jpg" alt="Hyderabadi chicken biryani">
<label for="d">Date to skip</label> <input type="date" id="d">
<button type="button" style="color:#1a1a1a;background:#fff">Skip</button>
</main></body></html>
Text
before: 7 violations
  color-contrast (serious, 1 node)
  document-title (serious, 1 node)
  html-has-lang (serious, 1 node)
  image-alt (critical, 1 node)
  landmark-one-main (moderate, 1 node)
  page-has-heading-one (moderate, 1 node)
  region (moderate, 4 nodes)
after: 0 violations

What axe didn't report is as instructive: the <div onclick> "button" can't be reached with Tab or activated with Enter/Space, so keyboard and screen-reader users can't skip a lunch at all, and the placeholder-only input (whose name disappears once you type) passed too. Automated tools catch roughly a third of WCAG issues; the rest need manual testing: keyboard-only navigation, a screen reader pass, zoom to 200% and 400% (reflow), and real users with disabilities.

L5 accessibility design: accessible component patterns built once in the design system (the WAI-ARIA Authoring Practices Guide describes keyboard and ARIA behaviour for tabs, menus, comboboxes, dialogs); focus management for SPAs (move focus to the new page's heading on route change; trap focus in modals and restore it on close); announcements for dynamic updates (aria-live regions for "Lunch skipped"); colour contrast in the design tokens (4.5:1 for body text, 3:1 for large text and UI components); motion preferences respected; error messages programmatically associated with fields.

L6: accessibility in the definition of done; axe in CI and component tests (jest-axe, Playwright + @axe-core/playwright); periodic manual audits; an accessibility statement and a feedback channel; tracking regressions like any other defect; training for designers and developers. Conformance is maintained, not achieved once: every release can regress it.

Lab: the rendering pipeline and the event loop, measured

Setup. Chromium (Playwright's pre-installed build, headless) on the lab machine; a page with a "Skip" button and 2,000 div rows. Timings come from performance.now() in the page and from the page's own click handler; each experiment was repeated.

Experiment 1: layout thrashing

JavaScript
// interleaved: forces layout 2,000 times
for (const r of rows) { const w = r.offsetWidth; r.style.width = (w + 1) + 'px'; }
// batched: read everything, then write everything
const ws = rows.map(r => r.offsetWidth); rows.forEach((r, i) => r.style.width = (ws[i] + 1) + 'px');
Version Six runs
interleaved reads and writes 764.0 / 804.9 / 798.2 / 765.6 / 879.4 / 831.5 ms
batched 7.9 / 6.3 / 7.8 / 6.6 / 7.6 / 6.7 ms

Same DOM, same final widths, over 100× faster. Each offsetWidth read after a style write forced a full synchronous layout of 2,000 elements. Performance traces show it as purple "Layout" blocks with a "Forced reflow" warning. Libraries (FastDOM, framework schedulers) and requestAnimationFrame batching exist to make the fast version the default.

Experiment 2: input delay from long tasks

A real mouse click (via Playwright) 30 ms after work starts on the main thread; delay = time from the click being sent to the handler running:

Main thread Input delay, three runs
idle 3 / 1 / 1 ms
one 500 ms task 470 / 466 / 470 ms
500 ms of work in 50 ms chunks, yielding with setTimeout(0) between 21 / 20 / 21 ms

The click waited for the long task to finish; with chunks, it ran after at most one chunk. Real apps hit this with large JSON parsing, big re-renders, synchronous analytics or heavy third-party scripts. Tools: break up work (scheduler.yield() where supported, setTimeout, requestIdleCallback), move it off the main thread (Web Workers), render less (virtualised lists), and measure INP in the field, since lab devices are faster than users' phones.

(A first measurement used the event's own timeStamp, which Chromium sets when the event is dispatched, after the long task; it reported near-zero delay for every case. Measuring from when the input was sent revealed the wait. Knowing what a timestamp means is part of L4.)

Try it yourself

  1. Record a performance trace of Experiment 1 in Chrome DevTools and find the forced-reflow warnings.
  2. Move the 500 ms work into a Web Worker and remeasure input delay.
  3. Throttle the CPU 4× in DevTools and remeasure both experiments.
  4. Use the web-vitals library to log INP on a real page you own and find its slowest interaction.

Revision sheet: frontend depth I

Key ideas

  • HTML semantics are a contract: native elements bring focus, keyboard behaviour and accessibility roles.
  • CSS at L3: cascade, specificity and layers; box model; formatting contexts; flexbox and grid algorithms; containment.
  • JavaScript's execution model: one main thread, task and microtask queues, rendering opportunities; promises and async/await; memory and closures.
  • TypeScript: structural typing, inference, narrowing, generics; deliberate unsoundness (any, bivariance, casts); designing types that make illegal states unrepresentable.
  • Browser internals: parse → style → layout → paint → composite; forced synchronous layout; compositor-only animations; network and caching.
  • Accessibility from first principles: the accessibility tree, names/roles/states, focus management, live regions, WCAG.

Numbers to remember

  • Lab: interleaved reads/writes on 2,000 rows ~800 ms vs batched ~7 ms.
  • Lab: click during a 500 ms task waited ~470 ms; chunked work ~20 ms.
  • INP good < 200 ms; aim for tasks < 50 ms.

Pitfalls

  • Reading layout properties inside write loops.
  • Long synchronous tasks on the main thread.
  • div buttons and ARIA used where native elements exist.
  • any and unchecked casts at system boundaries.
  • Measuring only on fast developer machines.

Glossary

  • Forced synchronous layout: layout computed immediately because script read geometry after a change.
  • Long task: main-thread work over 50 ms.
  • INP: Interaction to Next Paint.
  • Microtask: a job (e.g. promise callback) run before the next task.
  • Accessibility tree: the browser's semantic representation exposed to assistive technology.