Frame budget

A frame has 16.7 ms. A person notices at 100

16.7 msthe screen refreshes 60 times a second10 ms of script: done before the next refresh200 ms of script: 12 refreshes with no scroll or clickabout 100 ms: a person calls it slow0200 msAn interface gets 16.7 ms to draw each frame, and about 100 ms before a person notices the wait.On a 120 Hz screen the frame is 8.3 ms. Everything in this lesson, from layout to accessibility, is engineering insidethat envelope, on a device and a network the developer did not choose.

The frame budget: at 60 frames a second, everything needed for the next picture must finish in 16.7 ms.

Frame budget · Going deeper

The interface stack — from user input through the browser runtime down to the silicon User · eye · fingers Design system · tokens · components Framework · React · Vue · Svelte · Solid Web platform · DOM · CSSOM · Fetch · Workers Render pipeline · parse · style · layout · paint · composite JS engine · V8 · JSC · SpiderMonkey OS · GPU · CPU · pixels on glass every layer competes for the same 16.67 ms frame budget

The interface stack

From the user’s input down: framework, browser runtime (HTML parser, CSS engine, JavaScript engine sharing one DOM and one main thread), operating system, GPU, display. Every layer is replaceable and none is optional; a slow choice anywhere shows up as a missed frame at the top.

The main thread

One thread runs the script and draws the page

Task queueclick handlertimer callbacknetwork replythe main thread: one of these at a time1 Run one taskto completion2 Drain microtasksevery resolved promise3 Renderstyle, layout, paintthen the next taska task that runs 200 ms holds step 1, so step 3, the drawing, waits 200 ms tooOne thread runs your script, then promises, then draws. Whatever is slow blocks everything behind it.Promises drain before the render step, so an endless chain of them freezes the page just like a long loop. Heavy workbelongs in a Worker, or is cut into chunks that yield between inputs.

The event loop: run one task, drain the promises, render, repeat. All on the main thread.

The main thread · Going deeper · 1 of 2

The event loop — task queue, microtask queue, and the render step Task queue Microtask queue Render step setTimeout · I/O · postMessage Promise.then · queueMicrotask requestAnimationFrame click handler fetch complete setTimeout cb resolved promise mutation observer style layout paint composite one task per loop iteration drained completely before next task runs approximately every 16.67 ms a microtask that spawns microtasks can starve the render step — the source of "the page froze"

Tasks, microtasks and the render step

requestAnimationFrame runs a callback just before the next paint, the right moment for visual updates. requestIdleCallback runs when the thread is idle. scheduler.yield() lets a long task give way to input. The DOM is a C++ tree behind a binding layer, so each DOM write is a cross-boundary call the engine cannot optimise like plain arithmetic.

The main thread · Going deeper · 2 of 2

JS engine pipeline — parse, bytecode, baseline JIT, optimising JIT, deopt source.js bytecode baseline optimised parse · AST approximately 1 ms / 100 KB Ignition interpret Sparkplug non-optimising TurboFan type-specialised deopt · shape changed, type guard failed hot-path triggers function called approximately 100 times loop with stable types monomorphic call site deopt triggers adding a property after construction passing a different type to a hot function `delete obj.x` on a shaped object

The JavaScript engine is a compiler

V8, JavaScriptCore and SpiderMonkey interpret cold code as bytecode and recompile hot functions to machine code using the types they observed. If an object’s shape then changes, the function deoptimises: from about 10 ns a call back to 200 ns. A generational garbage collector frees short-lived objects cheaply; old-generation collections can pause for 30 ms or more.

Rendering pipeline

Which property you change decides how much is redone

Parse6 msStyle3 msLayout7 msPaint2 msComposite0.4 msRasteron the GPUchange width or leftlayout and paint again on every frame: drops frames on a mid-range phonechange colorskips layout, still repaintschange transform or opacitycompositor only: smooth while script is busyA change enters the pipeline at one stage and reruns everything after it. Enter as late as you can.Timings: first frame of a 2,400-element article on a 2023 laptop, about 18 ms on the main thread. Scrolling afterwards iscomposite-only, which is why it stays smooth. Reading a size right after writing one forces layout at once: layout thrashing.

The render pipeline: parse, style, layout, paint, composite, raster. A change reruns from its stage onward.

Rendering pipeline · Going deeper

Layout thrashing — interleaving reads and writes forces a synchronous layout per pair Thrashing · 50 ms Batched · 4 ms for (let el of items) { el.style.width = "200px" let h = el.offsetHeight // sync layout el.style.height = h + 10 + "px" let w = el.offsetWidth // sync layout } // 100 items × 2 reads × 0.25 ms // = 50 ms · drops 3 frames // read phase const ws = items.map(e => e.offsetWidth) const hs = items.map(e => e.offsetHeight) // write phase items.forEach((e, i) => { e.style.width = ws[i] + "px" e.style.height = hs[i] + 10 + "px" }) // 1 layout total · 1 paint read-then-write batching is the cheapest performance win on a list-heavy page

Layout thrashing

The browser defers layout to the next frame. Reading a geometry property such as offsetTop or getBoundingClientRect after a style write forces it to lay out immediately. Interleave reads and writes in a loop and each iteration pays a full layout. The fix: batch all reads, then all writes.

Check yourself

StyleLayoutPaintCompositeA left: 0 → 300pxB transform: translateX(300px)

A card slides 300 px across the screen. Version A animates left; version B animates transform. The phone is busy running script. Which stays smooth?

CSS cascade

CSS picks one winning rule per property, by a fixed ladder

<button id="buy" class="btn primary">four rules set its backgroundIDsclassestypes.btn.primary { background: blue }020.btn { background: grey }010button { background: white }001#buy { background: green }100winscompared left to right: one ID outranks any number of classesthe ladder, top rung firstOrigin and !importantLayer (@layer)SpecificitySource order: later winsa tie moves down one rungFor each property the browser picks exactly one winning rule, by a fixed ladder.“Why is my style ignored” is always answered by a rung. Cascade layers, added in 2022, let a later layer beat an earlier onewhatever the specificity, so app styles reliably override a design-system base.

The cascade resolves competing rules by origin, layer, specificity, then source order.

CSS cascade · Going deeper

Flexbox versus Grid — one-dimensional flow versus two-dimensional placement Flexbox · 1D Grid · 2D main axis + cross alignment tracks + named areas flex: 1 flex: 2 auto main axis header nav main aside when rows of buttons card lists wrapping toolbar alignment when page-level layout dashboards with cross-row alignment photo galleries with `grid-auto-flow: dense`

Two layout engines: Flexbox and Grid

Flexbox lays children along one axis: toolbars, button rows. Grid places them in two dimensions: page shells, dashboards. Most pages use Grid for the shell and Flexbox inside cells. Container queries let a component respond to its parent’s size, and contain tells the browser a subtree cannot affect the rest of the page, so work can be skipped.

UI state

Where state lives decides how much of the screen re-renders

state at the top, everyone subscribedone keystroke: 10 of 10 re-renderdatadowneventsuponly the reader of the value subscribesone keystroke: 1 of 10 re-rendersA state change re-renders whoever subscribes to it. Narrow the subscription and the app scales.A 200-component app survives anything; a 20,000-component dashboard on one global store drops frames on every keystroke.Keep state local, lift it to a shared parent only when siblings need it, and subscribe narrowly to anything global.

In a component tree, data flows down and events flow up. A state change re-renders its subscribers.

UI state · Going deeper · 1 of 2

Three reactivity models — vDOM diff, signals, and compiled updates Virtual DOM Signals Compiled React Solid · Vue 3 · Svelte 5 runes Svelte (template) state.x = 5 component() returns vDOM diff(old, new) apply patches signal.set(5) notify subscribers text node 7 update node 7 x = 5 compiler emitted: textNode.data = 5 done cost per update O(component subtree) memoise to scope cost per update O(subscribers) tracked at runtime cost per update O(1) for known writes tracked at compile main risk over-render on big trees main risk losing reactivity scope main risk bespoke template syntax all three converge on the same goal — update only what changed — by different routes

Three ways to know what to update

Virtual DOM (React) re-runs the component and diffs the new tree against the old: simple to reason about, costs CPU per update. Signals (Solid, Vue 3, Svelte 5) track which DOM nodes read which value and update only those: no diff. Compiled reactivity (Svelte) emits the DOM writes at build time.

UI state · Going deeper · 2 of 2

Data flows down, events flow up — three state scopes App Header Sidebar Form List user · onLogout user · onNav local form state subscribes to store props ↓ props ↓ events ↑ events ↑ local form input · disclosure open lifted shared between siblings · still tree-local global cross-tree · explicit subscription · selector-scoped

Three scopes of state

Local state lives and dies with one component. Lifted state moves to a common ancestor so siblings can share it, and re-renders that subtree. Global state survives the tree and needs explicit subscriptions. Choosing the wrong scope is the usual cause of “the whole app re-renders on every keystroke”.

Rendering strategies

Where the HTML is made sets how long the user waits

blankvisible, but taps do nothing yetinteractiveClient (CSR)browser builds the pagestill blank at 3 s on a content site: script must download, run and fetch data firstServer (SSR)HTML made per request400 to 800 ms that looks ready and is not: the script is still attaching handlers (hydration)Static (SSG)HTML made at buildfirst byte in 10 to 30 ms from a CDN; hydration still to payIslandsstatic + small live parts5 to 20 KB of script instead of 200 KB: only the live parts hydrate03 smid-range phone; lengths are illustrative except the labelled figuresWhere the HTML is produced decides how long the user looks at a blank or frozen page.Each step toward build time or the server cuts shipped script and speeds first paint; each step toward the client buys richerinteraction. Pick the cheapest that meets the need: content sites static with islands, signed-in apps server-rendered.

CSR, SSR, SSG and islands are points on one trade-off. Hydration is the gap between looking ready and being ready.

Rendering strategies · Going deeper · 1 of 2

Rendering strategies on the TTFB / LCP / TTI trade-off CSR SSR SSG Streaming SSR Islands TTFB LCP TTI JS bundle: 200 KB JS bundle: 200 KB JS bundle: 0–80 KB JS bundle: 200 KB JS: 5–20 KB no SEO content SEO good SEO best SEO good SEO best bar height ≈ time on a fast 4G connection · darker = main-thread blocking

The strategies on one chart

Streaming SSR flushes the shell first and streams content as data resolves, so the user sees pixels at 100 ms even if the slowest query takes 800. Incremental static regeneration serves cached pages and rebuilds stale ones. Edge rendering moves the server to CDN locations: about 50 ms to first byte worldwide, in a constrained runtime.

Rendering strategies · Going deeper · 2 of 2

Hydration timeline — SSR full hydrate versus partial hydrate versus resumable SSR (full hydrate) Islands (partial) Resumable (Qwik) 0 ms 200 ms 500 ms 1 s 2 s HTML JS download + parse + hydrate interactive HTML island island interactive on first paint HTML + serialised state listeners wired lazily on first interaction first paint

Hydration, partial hydration, resumability

Partial hydration (Astro) hydrates only marked components. Resumability (Qwik) serialises framework state into the HTML so the client never re-runs setup. React Server Components run only on the server and ship no script for themselves.

The browser platform

The browser has become a small operating system

Networkfetch, streamsWebSocketsSSE: server pushesStoragelocalStorage: 5 MBIndexedDB: GBsCache API, filesThreadsWeb WorkerService Workeroff the main threadMediacamera, micWebRTCpeer-to-peer callsGraphicsWebGL2WebGPUin-browser MLComputeWebAssemblyC++, Rust, Gonear-native speedPagecalls fetch()Service Workerintercepts every requestCache: works offlineNetworkinstalled once, it sits between thepage and the network: offline use,install to home screen, pushThe browser is a small operating system: sockets, databases, threads, a GPU and a second language.Fetch, Streams, IndexedDB, Service Workers, WebSockets and WebRTC work everywhere. WebUSB, WebHID and WebNFC ship onlyin Chromium browsers, so detect a capability before using it and degrade gracefully.

The web platform exposes networking, storage, threads, media, graphics and compiled code through standard APIs.

The browser platform · Going deeper

The browser as an operating system — capability APIs grouped by domain Networking Storage Compute fetch() Streams WebSocket EventSource (SSE) WebRTC WebTransport Beacon Service Worker localStorage sessionStorage IndexedDB Cache API OPFS Cookie Store FileSystem API storage quota Web Workers SharedWorker Service Worker WebAssembly WebGPU WebGL2 Canvas / OffscreenCanvas Web Audio Media · Input · Device getUserMedia Pointer Events Web MIDI WebHID WebUSB Geolocation MediaStream Keyboard Lock Gamepad WebNFC (Android) Vibration Wake Lock availability varies by browser and platform — check `caniuse.com` before reaching for the obscure ones

Capabilities by domain

Web Workers run script on another OS thread with no DOM access, communicating by postMessage. WebAssembly pays off for CPU-bound work, as in Figma’s vector engine or in-browser SQLite, but calls across the JS boundary are not free. WebGPU exposes the explicit model of Vulkan and Metal and is used for in-browser ML inference.

Core Web Vitals

Perceived speed is three numbers you can measure

goodpoorLCPLargest Contentful Paintwhen the main content shows2.5 s4 sINPInteraction to Next Paintslowest tap to visible response200 ms500 msCLSCumulative Layout Shifthow much the page jumps0.10.25judged at the 75th percentile of real visits, not on your laptopPerceived speed is three measured numbers: is it visible, does it respond, does it stay still.Under 200 ms feels instant, under 1 s keeps attention, over 10 s the user has left. Reserve space for images, ads and fontswith explicit sizes and the page stops jumping.

Core Web Vitals: LCP under 2.5 s, INP under 200 ms, CLS under 0.1, at the 75th percentile of real users.

Core Web Vitals · Going deeper

Core Web Vitals — LCP, INP, CLS — with target ranges LCP INP CLS largest paint tap → next paint layout shift good needs work poor ≤ 2.5 s 2.5–4 s > 4 s good needs work poor ≤ 200 ms 200–500 > 500 good needs work poor ≤ 0.1 0.1–0.25 > 0.25 levers preload LCP image AVIF / WebP font swap cut render-blocking JS levers break long tasks debounce expensive work workers for heavy compute CSS containment levers explicit `width` / `height` reserve space for ads `size-adjust` for fonts `min-height` skeletons measured at the 75th percentile across real users — synthetic numbers do not count

The thresholds and how they are measured

INP replaced First Input Delay in 2024. For CLS, give every image and embed explicit width and height, reserve slots for ads, and match fallback font metrics so the font swap is invisible. Field data comes from real users through the web-vitals library or the Chrome UX Report; lab tools only approximate it.

Page load

Most of a page load is spent before your code runs

landing page on a mid-range phone over 4G, in milliseconds, to scaleDNS 30TCP + TLS 200server 200HTML 50image 130decode 30network before the first byte of HTML: 430 msmain content painted at 640 msbudget 2.5 sthe same page on a five-year-old Android phone2 s with little script9 s with 500 KB of scriptWalk the budget: the time is network and image first, then script on slow phones. Rarely the framework.Biggest levers: a modern image format (AVIF is about half the bytes of JPEG), preloading the main image, and shipping lessscript, later. Every kilobyte of script costs parse and run time on the device, not just download.

A worked performance budget: network and image dominate; on slow phones, script does.

Page load · Going deeper · 1 of 2

Worked LCP budget — request through paint on a mid-range phone over 4G LCP walk · target 2.5 s · arrived 640 ms 0 100 200 400 600 800 ms DNS 30 ms TCP + TLS 80 ms TTFB 80 ms HTML 50 ms image download 130 ms decode 50 ms paint 15 ms request LCP fires every box is a lever — TTFB, format, preload, decode priority

The worked budget, step by step

Levers in order of effect: AVIF or WebP for the main image, preload with fetchpriority="high" (50 to 100 ms), inline critical CSS, route-level code splitting, lazy loading below the fold, font subsetting (a Latin subset can drop 400 KB to 30 KB), and 103 Early Hints.

Page load · Going deeper · 2 of 2

INP — input → next paint with and without a long task in the way Good · 80 ms INP Bad · 340 ms INP 0 100 ms 200 ms 300 ms 400 ms tap delay handler 40 ms paint tap blocked by long task 144 ms handler style + layout 96 ms paint

INP and the long task

A long task is anything over 50 ms on the main thread. A 250 KB compressed bundle parses in roughly 100 ms on a mid-range phone. INP records the worst interaction of the session, so one pathological tap on an old phone defines the score. Break work up with scheduler.yield() and move hashing or large JSON parsing to a Worker.

Check yourself

0300 msone task on the main threadtap at 50 ms

The main thread is 50 ms into a 300 ms task when the user taps a button. Roughly when can the screen first show a response?

Accessibility and native elements

A native element is a contract. A div is a rectangle

<button><div onclick>reachable with the Tab keyyesnoEnter and Space activate ityesnoannounced as “button”yesnocan submit its formyesnoabout 16% of people, over a billion, live with a disabilityHTML<label for="email">Email</label><input id="email" type="email">Accessibility treerole: text field · name: “Email”Screen reader says“Email, edit text”A native element comes with keyboard, focus and screen-reader behaviour built in. A div comes with none.Use the native element when one exists; add ARIA only where HTML has none for the job, because a wrong role lies to the user.Automated checkers catch about a third of problems; the rest needs a keyboard walk-through and a screen reader.

Semantic HTML gives keyboard, focus and screen-reader behaviour for free. ARIA only patches the gaps.

Accessibility and native elements · Going deeper · 1 of 2

The accessibility layer — semantic HTML, ARIA, focus, keyboard, screen reader DOM + accessibility tree DOM Accessibility tree <button>Save</button> native semantics + state <a href="/x">link</a> link role · href required <input aria-label="search"> accessible name patched in <div role="tab" tabindex="0"> custom · keyboard + role needed button "Save" focusable · pressable · enabled link "link" → /x focusable · activates URL textbox "search" editable · single-line tab "Overview" (selected) in tablist · aria-selected=true screen readers read the accessibility tree, not the DOM — every visual element needs a tree counterpart

The accessibility layer

ARIA supplies role, name and state when HTML cannot: role="tab", aria-expanded, aria-live. “No ARIA is better than bad ARIA”: a stale state misleads. For errors: aria-invalid on the input, aria-describedby pointing at the message, a live region for the summary, and focus moved to the first invalid field. Body text needs 4.5:1 contrast; #999 on white is about 2.8:1.

Accessibility and native elements · Going deeper · 2 of 2

Focus order on a sign-up form — tab moves through fields in reading order Email · type=email · aria-describedby="email-err" Password · type=password Confirm password · type=password Email me about updates · checkbox Create account 1 2 3 4 5 "Email, edit text, required" "Password, edit text" "Confirm password, edit text" "Email me, checkbox, not checked" "Create account, button" tab order matches visual order matches screen-reader order — three views of the same sequence

Focus order on a real form

Tab should follow reading order. Positive tabindex values break it and are almost always wrong. A placeholder is not a label: it vanishes on the first keystroke. Dialogs trap focus and close on Esc; a skip link lets keyboard users pass the navigation; the focus ring must stay visible.

Check yourself

Email<input>Password<input>Sign up<div onclick>Tab?

In this form, “Sign up” is a styled <div> with a click handler. A keyboard user fills both fields and presses Tab. What happens?

Mobile and cross-platform

Three routes reach a phone; one source keeps them consistent

routecodewhat you getNativethe platform’s own toolkitSwiftKotlinevery OS feature the day it shipsbest speed and battery; two teamsCross-platformReact Native, Flutterone codebaseone team ships to both phonesnew OS features arrive months lateInstalled web appa PWAthe websiteno store, instant updateslimited device access, less on iOSDesign tokenscolour, spacing, typeWebiOSAndroidone change, one pull request,every surface updatedThree routes reach a phone, each trading cost against access to the device.Native pays off when the app is the product and people use it daily. Across all routes, one source of design tokens and asmall set of shared components, 15 to 25, stops every team re-deciding the same button.

Native, cross-platform and installed web apps trade cost for device access. Design tokens keep them aligned.

Mobile and cross-platform · Going deeper · 1 of 2

Mobile delivery paths — native, cross-platform, PWA — on the cost / capability trade-off Native Cross-platform PWA Swift · Kotlin React Native · Flutter web · Service Worker capability full · day-1 OS APIs performance best · native widgets team cost 2 codebases · 2 teams ship velocity app-store review (1–7 days) when it wins flagship app, daily use capability most · plugin gap performance near-native (Fabric) team cost 1 codebase · platform shims ship velocity app-store review still applies when it wins 2 platforms, small team capability web platform subset performance good · main-thread JS team cost 1 codebase · web team ship velocity instant — no review when it wins content, light interaction most teams ship a web product first, then a native app if engagement justifies it

Mobile delivery paths

React Native runs JavaScript and drives native views; its new architecture shrinks the bridge cost. Flutter draws every pixel itself with its own engine: consistent visuals, less platform feel. iOS constrains installed web apps more than Android does.

Mobile and cross-platform · Going deeper · 2 of 2

Design tokens flow — one source propagates to every platform tokens.json color.bg.primary space.4 · radius.md Web iOS Android CSS custom props --bg-primary Swift constants Color.bgPrimary Compose tokens MaterialTheme React · Vue · Svelte SwiftUI · UIKit Jetpack Compose Style Dictionary or similar emits per-platform output from one JSON source of truth

Design tokens

Tokens are named primitives such as --space-4 or --radius-md, kept in one file and exported to web, iOS and Android. Above them sit accessible components, then patterns such as sign-up or empty state. A type ramp of about seven sizes, line height 1.5 for body text and 45 to 75 characters a line carry most screens.

Target size

Bigger and closer is faster to hit, and it is measurable

time = a + b × log2(distance ÷ width + 1)width 20, distance 400: 4.4 bits of difficultywidth 80, same distance: 2.6 bits, faster to hitminimum touch targets, drawn at actual sizeiOS: 44 × 44 ptAndroid: 48 × 48 dpa 20 px icon: missed tapsTime to hit a target grows with its distance and shrinks with its size. Fitts measured it in 1954.Screen edges act as huge targets because a pointer cannot overshoot them. Feedback later than about 200 ms feelsdisconnected from the tap: a 200 ms ease-out shows where a panel came from, a 600 ms one feels slow.

Fitts’s law: pointing time grows with distance and shrinks with target size.

Summary

An interface: a budget of milliseconds, a contract with every user

A persontap, key, voiceMain threadone task at a timePipelinestyle, layout, paintA frameevery 16.7 msWhere HTML is madebuild, server or clientMeasured2.5 s, 200 ms, 0.1For everyonenative elements, keyboardEvery surfaceweb, native, shared tokensAn interface is a budget of milliseconds and a contract with every kind of user.Declare in HTML and CSS what the browser can optimise for you; spend script, the one contended thread, where it paysthe user back.

One thread, one pipeline, 16.7 ms a frame, for every kind of user. Next: engineering craft, how teams build all this.

Summary · Going deeper

The interface stack — from user input through the browser runtime down to the silicon User · eye · fingers Design system · tokens · components Framework · React · Vue · Svelte · Solid Web platform · DOM · CSSOM · Fetch · Workers Render pipeline · parse · style · layout · paint · composite JS engine · V8 · JSC · SpiderMonkey OS · GPU · CPU · pixels on glass every layer competes for the same 16.67 ms frame budget

The interface stack, top to bottom

The web platform is the most heavily specified surface in software: living standards from WHATWG, W3C Recommendations, and WCAG for accessibility. HTML and CSS are declarations the browser can optimise heavily; JavaScript is the escape hatch that costs main-thread time.

Lesson complete

You finished “Interfaces”

Answer the questions along the way to see your score here.

Open in a new tab