The Web FrontendVol. 2 · Part II
0 / 0

Shelves / The Web Frontend

FE·12

The Web Platform

The core concepts every other frontend chapter builds on: URLs, origins, browsing contexts, documents, navigation, resource loading, the DOM, CSSOM and accessibility trees, the JavaScript runtime, storage, and the browser's security model.

33 topics · ~29 min read · 27-question quiz
Updated Suggest a correction

Start here: the browser as a place where programs run

The browser is an operating system for web pages

On your computer, the operating system runs programs, keeps them apart, and gives them services: files, network, a screen (Volume 1, chapter 8). A browser does the same job for web pages:

Operating system Browser
runs programs runs pages (each with its own HTML, CSS and JavaScript)
a file path names a program a URL names a page or resource
user accounts keep programs' data apart origins keep sites' data apart
a process is a running program a document is a loaded page in a tab or frame
system calls (files, network) web APIs (fetch, storage, camera, notifications)
permissions (can this program read that file?) the security model (can this site read that site's data?)

This chapter is a tour of that platform: the parts every other chapter relies on. The full-depth sections after this one then explain each part properly.

URLs: the address of everything

Every page, image, script and API endpoint has a URL (Uniform Resource Locator). The browser's URL class takes one apart (run in Node; it's the same class in browsers):

JavaScript
const u = new URL("https://shop.example.co.in:8443/menu/dosa?size=large&spicy=yes#reviews");
console.log(u.protocol, u.hostname, u.port, u.pathname, u.search, u.hash, u.origin);
console.log(u.searchParams.get("size"));
Text
protocol  https:
hostname  shop.example.co.in
port      8443
pathname  /menu/dosa
search    ?size=large&spicy=yes
hash      #reviews
origin    https://shop.example.co.in:8443
size param: large
  • The scheme (https:) says how to fetch it.
  • The host says which server; the port which program on it (443 is assumed for https, 80 for http, so you rarely see them).
  • The path says which resource on that server, like a file path.
  • The query (?size=large&spicy=yes) passes named values, like arguments to a function.
  • The fragment (#reviews) never leaves the browser: it scrolls to an element, or a single-page app uses it for routing.

Links inside a page are usually relative, resolved against the page's own URL, just like relative paths in a terminal:

Text
page: https://example.com/docs/guide/intro.html
setup.html               → https://example.com/docs/guide/setup.html
../api.html              → https://example.com/docs/api.html
/about                   → https://example.com/about
?page=2                  → https://example.com/docs/guide/intro.html?page=2
#install                 → https://example.com/docs/guide/intro.html#install
//cdn.example.net/x.js   → https://cdn.example.net/x.js

Spaces and symbols like & have special meanings in URLs, so values must be encoded: encodeURIComponent("masala dosa & chai") gives masala%20dosa%20%26%20chai, and searchParams.get decodes it back. Building URLs by gluing strings together without encoding is a classic bug; use URL and URLSearchParams.

Origins: the browser's unit of trust

An origin is the triple scheme + host + port. Two URLs are same-origin only if all three match:

Text
https://example.com  vs  https://example.com:443/a: same origin
https://example.com  vs  http://example.com: different origin
https://example.com  vs  https://www.example.com: different origin
https://example.com  vs  https://example.com:8443: different origin

Think of origins as flats in an apartment building: each flat has its own lock, its own cupboards (storage), and residents can't walk into each other's flats. Even localhost and 127.0.0.1, which reach the very same server, are different origins, so they get separate storage (checked in Chromium below). Almost every security rule in the browser is stated in terms of origins.

Documents and the DOM tree

When the browser loads an HTML page, it creates a document and parses the HTML into a tree of nodes. For this small page:

HTML
<!doctype html><html lang="en"><head><title>Menu</title></head>
<body><h1>Menu</h1><ul><li>Dosa</li><li>Idli</li></ul></body></html>

the tree is (element nodes by name, text nodes in quotes):

Text
html
  head
    title
      "Menu"
  body
    h1
      "Menu"
    ul
      li
        "Dosa"
      li
        "Idli"

That tree is the DOM. JavaScript reads and changes it (document.querySelector("h1").textContent = "Lunch menu"), and the screen updates to match. The browser also builds a CSSOM (the parsed style rules) and an accessibility tree (what screen readers announce), both explained below.

HTML parsing never fails. Faced with broken markup, the parser follows precise recovery rules written into the HTML standard, so every browser builds the same tree. Feeding Chromium sloppy HTML:

Text
input:  <p>One<p>Two <b>bold <i>both</b> italic?</i><table><tr><td>cell</table>
DOM:    <p>One</p><p>Two <b>bold <i>both</i></b><i> italic?</i></p><table><tbody><tr><td>cell</td></tr></tbody></table>

The parser closed the paragraphs, re-nested the overlapping <b>/<i> and added the <tbody> you didn't write. Convenient, but it means the DOM can differ from what you think you wrote; the Elements panel always shows the truth.

Loading: the browser reads top to bottom

The parser works through the HTML from top to bottom, building the tree as it goes and requesting each resource it meets (stylesheets, images, scripts). A plain <script> pauses parsing until it has downloaded and run, because the script might change the page being parsed. One slow script in the <head> therefore delays everything below it. That's why the Start Here chapter's script couldn't find the button, and why modern pages use defer or type="module". The lab at the end of this chapter measures exactly how long each kind of script delays the page.

Where pages keep data

A web page's JavaScript variables vanish when you reload. To remember things, pages use browser storage, and each origin gets its own:

Storage Lifetime Good for
Cookies until they expire login sessions (sent to the server with every request)
localStorage until cleared small preferences (theme, language)
sessionStorage this tab only, until it closes per-tab state (a half-filled form)
IndexedDB until cleared or evicted large structured data, offline apps

Checked in Chromium: a page stores a theme in localStorage, a tab name in sessionStorage, and a plain variable; then it reloads, opens a second tab, and finally visits the same server as 127.0.0.1:

Text
after reload: {"theme":"dark","tab":"orders","inMemory":null}
new tab:      {"theme":"dark","tab":null,"inMemory":null}
127.0.0.1:    {"theme":null}

The variable didn't survive the reload; sessionStorage didn't follow you into a new tab; and a different origin (even for the same server) sees none of it.

The security model in one paragraph

You visit dozens of sites a day, and any of them could be malicious. The browser protects you with the same-origin policy: a page can send requests almost anywhere (that's how links, images and forms work), but its JavaScript can read only its own origin's pages, storage and responses, unless the other origin explicitly allows it (CORS, chapter 19). The lab shows it happening: a page on localhost:8001 asks localhost:8002 for an account balance; the request reaches the server, but the browser refuses to hand the answer to the script. Add on that sandboxed processes keep each site's memory apart, and HTTPS keeps the network honest, and you have the core of web security (chapter 28).

How deep to go in the web platform

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 parts of a URL, define origin, document, DOM and storage types
L2 Build and parse URLs safely, choose the right storage, load scripts without blocking
L3 Explain origins vs sites, navigation and history, how the trees are built, the event loop's place in the page, and the layers of the security model
L4 Diagnose blocked requests, missing storage, script-ordering bugs and back-forward-cache misses with DevTools
L5 Design an app's loading strategy, storage and origin layout (subdomains, cookies, isolation headers)
L6 Operate it: storage eviction and quota at scale, origin migrations, security headers across many apps

The browser as a platform

What "the web platform" means

A web browser is an operating system for documents and applications. It downloads code from strangers, runs it in a sandbox, gives it a rendering engine, a networking stack, storage, threads (workers), a GPU, cameras, and a security model, and it does this for billions of people on every kind of device. The web platform is the set of standards that define all of that:

Standard Body Defines
HTML Living Standard WHATWG Elements, parsing, the event loop, navigation, browsing contexts, storage, workers
DOM Living Standard WHATWG Nodes, trees, events, AbortController, mutation observers
URL, Fetch, Streams, Encoding WHATWG URL parsing, every network request, CORS, streaming bodies
CSS specifications W3C CSS WG Layout, cascade, selectors, colours, animations (dozens of modules)
ECMAScript (ECMA-262) Ecma TC39 The JavaScript language itself, yearly editions (ES2015 … ES2026)
WebAssembly W3C WebAssembly WG A portable bytecode (Vol. 1 ch. 10)
WAI-ARIA, WCAG W3C WAI Accessibility semantics and conformance
HTTP (RFC 9110–9114), TLS, QUIC IETF The wire protocols

The WHATWG standards are living standards: there's no "HTML6", just a continuously updated spec, and browsers ship features when they're ready. That's why the practical questions are "which browsers support this?" and "is it Baseline?" MDN and web.dev label features Baseline Newly available once all major engines (Chromium/Blink, Firefox/Gecko, Safari/WebKit) ship them, and Baseline Widely available 30 months after that.

Only three rendering engines remain: Blink (Chrome, Edge, Opera, Brave, Samsung Internet, Electron), Gecko (Firefox), and WebKit (Safari, and every browser on iOS until recent EU rule changes allowed other engines there). Compatibility work today is mostly about Safari and older Safari versions on iPhones that haven't been updated.

The platform compared with a native runtime

It helps to map browser concepts onto things you know from Volume 1:

OS / native concept (Vol. 1) Browser equivalent
Process with an address space A renderer process per site (site isolation)
Program binary HTML + CSS + JS + Wasm downloaded per visit
Main thread + event loop The page's main thread running the HTML event loop
Threads Web Workers (no shared DOM; message passing, optional SharedArrayBuffer)
System calls Web APIs (fetch, localStorage, navigator.mediaDevices) mediated by the browser
File system Origin-scoped storage: cookies, localStorage, IndexedDB, Cache Storage, OPFS
User / permissions The origin: the unit of trust and isolation
Dynamic linking ES module imports, <script> tags, import maps
Package install HTTP caching + service workers

The key difference from native development is that every page load is a fresh install of untrusted code over the network. Performance work is mostly about loading; security work is mostly about the origin boundary; architecture work is mostly about what runs on the main thread.

URLs and origins

Anatomy of a URL

A URL (uniform resource locator) identifies a resource and how to fetch it. The WHATWG URL Standard defines exactly how browsers parse it:

Text
  https://user:pass@shop.example.com:8443/cart/items?id=42&sort=desc#reviews
  └─┬─┘   └───┬───┘ └──────┬───────┘ └┬─┘└────┬────┘└───────┬──────┘└──┬───┘
 scheme  userinfo        host        port   path        query      fragment
         (avoid)                                       (search)    (hash)
  • Scheme: https, http, file, data, blob, mailto, javascript (dangerous; see chapter 28).
  • Host: a domain name or IP address. Internationalised names are converted to ASCII punycode (münchen.de → xn--mnchen-3ya.de).
  • Port: defaults to 443 for https and 80 for http when omitted.
  • Path: hierarchical, /-separated. Relative URLs resolve against a base URL (the document's URL, or <base href>).
  • Query: key=value pairs, conventionally application/x-www-form-urlencoded.
  • Fragment: never sent to the server. The browser uses it to scroll to an element with that id, and single-page apps once used it for routing (#/users/1).

Percent-encoding escapes reserved or non-ASCII bytes as %HH (UTF-8 bytes, Vol. 1 ch. 6): a space becomes %20 (or + in form-encoded queries), and é becomes %C3%A9. Use the built-in APIs instead of string concatenation, which is a common source of injection and double-encoding bugs:

const u = new URL("/search", "https://shop.example.com");
u.searchParams.set("q", "red shoes & socks");
u.searchParams.append("page", "2");
u.toString();          // "https://shop.example.com/search?q=red+shoes+%26+socks&page=2"
u.origin;              // "https://shop.example.com"
new URL("../img/a.png", "https://x.com/a/b/c.html").href;   // "https://x.com/a/img/a.png"

Origins

The origin is the most important security concept on the web. An origin is the triple (scheme, host, port):

URL Origin Same origin as https://app.example.com?
https://app.example.com/a/b https://app.example.com (port 443) ✓
https://app.example.com:443/x same ✓ (443 is the default)
http://app.example.com http://app.example.com ✗ scheme differs
https://api.example.com https://api.example.com ✗ host differs
https://app.example.com:8443 https://app.example.com:8443 ✗ port differs

Almost every browser protection is scoped to the origin: DOM access between windows, storage (localStorage, IndexedDB, Cache Storage), permissions (camera, notifications), and which responses JavaScript may read (the same-origin policy, chapter 19). Some URLs have opaque origins that match nothing, not even themselves: data: URLs, sandboxed iframes, and file: in most browsers.

Sites and schemeful sites

A site is broader than an origin: the scheme plus the registrable domain (eTLD+1), which is the public suffix plus one label. app.example.com and api.example.com are same-site (https://example.com) but cross-origin. The browser looks up public suffixes in the Public Suffix List, so user1.github.io and user2.github.io are different sites (github.io is a public suffix), and bbc.co.uk is the registrable domain, not co.uk.

"Site" governs cookies' SameSite attribute (chapter 19), site isolation (one renderer process per site, chapter 18), and cross-site request metadata (Sec-Fetch-Site). Remember the two words precisely:

  • Same-origin: scheme, host and port all equal.
  • Same-site: scheme and registrable domain equal. Subdomains and ports may differ.

Browsing contexts and documents

Windows, tabs, frames and navigables

A browsing context (in current spec language, a navigable plus its traversable history) is an environment that displays a sequence of documents: a tab, a popup window, or an <iframe>. Each has:

  • A session history: the list of documents it has shown, which back and forward walk.
  • An active document: the Document currently shown.
  • A Window object (globalThis in page scripts), which is the global scope for that document's scripts.
  • A relationship to others: window.parent, window.top, window.opener (the window that opened a popup), and child frames via window.frames.

Browsing context groups are sets of contexts that can reach each other through script references (an opener and its popup, a page and its iframes). Contexts in the same group might need to share a process, which weakens isolation. Cross-Origin-Opener-Policy: same-origin (chapter 28) puts your page in its own group, severing window.opener links to cross-origin pages. It's required for "cross-origin isolation", which unlocks SharedArrayBuffer and high-resolution timers.

The Document

The Document is the root object for a loaded page: the parsed tree of nodes, plus metadata.

JavaScript
document.URL;             // the document's address
document.documentElement; // <html>
document.head, document.body;
document.title;
document.readyState;      // "loading" → "interactive" (parsed) → "complete" (subresources loaded)
document.visibilityState; // "visible" | "hidden" (background tab, minimised)
document.cookie;          // the legacy cookie API (string-based, synchronous)
document.characterSet;    // "UTF-8"
document.compatMode;      // "CSS1Compat" (standards mode) or "BackCompat" (quirks mode)

Quirks mode emulates 1990s browser bugs for pages without a proper doctype. A missing or wrong <!doctype html> changes the box model and table layout in surprising ways, so every page must start with <!doctype html>.

Lifecycle events you'll use:

Event Fires when Use for
DOMContentLoaded (on document) HTML fully parsed, deferred scripts run; images may still be loading Starting app code that needs the DOM
load (on window) Every subresource (images, iframes, stylesheets) finished Rarely needed now
visibilitychange Tab hidden or shown Pausing work; the last reliable moment to save state or send analytics
pagehide / pageshow Navigating away / back, including from the back-forward cache Cleanup and restoring state
beforeunload About to leave Only for "unsaved changes" prompts. It disables the bfcache in some browsers
unload Being destroyed Don't use it: unreliable on mobile, blocks the bfcache, and is being deprecated in Chrome

Navigation and session history

Navigation loads a new document into a browsing context: clicking a link, submitting a form, location.href = …, or the back button. A full navigation:

  1. Runs beforeunload on the current document.
  2. Fetches the new URL (following redirects), or restores the document from the back-forward cache (bfcache), which keeps a frozen copy of the whole page in memory for instant back and forward navigation.
  3. Creates a new Document and Window, parses the response, and runs the new page's scripts.
  4. Adds a session history entry.

Same-document navigation changes the URL without loading a new document. Fragment navigation (#reviews) does this, as does the History API (history.pushState(state, "", "/cart") and popstate) and, more recently, the Navigation API (navigation.navigate() with a navigate event you can intercept). It shipped first in Chromium and was an Interop 2025 focus area for the other engines, so check its Baseline status before relying on it. Single-page applications are built on this: the router intercepts link clicks, updates the URL with pushState, and renders the new view itself. The cost is that the app must reimplement what the browser did for free: scroll restoration, focus management (chapter 20), loading indicators and error handling. View Transitions (chapter 14) now animate both kinds of navigation.

JavaScript
// Navigation API: one place to handle every same-origin navigation
navigation.addEventListener("navigate", (event) => {
  const url = new URL(event.destination.url);
  if (!event.canIntercept || url.origin !== location.origin) return;
  event.intercept({
    async handler() {
      const view = await loadView(url.pathname);   // fetch data + render
      document.querySelector("main").replaceChildren(view);
    },
  });
});

Loading and the trees

Resource loading

A page is rarely one file. The HTML references stylesheets, scripts, fonts, images, video, iframes, and fetch() calls. The browser's preload scanner reads ahead in the HTML while the main parser is blocked and starts downloads early. Every request goes through the Fetch standard's algorithm: build a request (URL, method, headers, mode, credentials mode, destination), apply security checks (mixed content, CSP, CORS), check the HTTP cache and any service worker, go to the network, and process the response.

Resources differ in how they block the page:

Resource Blocks parsing? Blocks rendering?
<script> (classic, no attributes) Yes: parsing stops while it downloads and runs Yes
<script defer> / <script type="module"> No: runs after parsing, in order No
<script async> No: runs as soon as it arrives, in any order Briefly, while it runs
<link rel="stylesheet"> No, but later scripts wait for it Yes: nothing paints until it loads (avoids unstyled flashes)
Images, video, iframes No No (they fill in later, causing layout shift unless sized)
Fonts No Text may be invisible until the font loads (font-display controls this)

The critical rendering path is the minimum chain of resources needed for the first paint: HTML → CSS (render-blocking) → any synchronous scripts → fonts for visible text. Chapter 27 is about shortening it. Resource hints (chapter 13) let you influence priority: preload, preconnect, modulepreload, fetchpriority.

The DOM

The Document Object Model is the live, in-memory tree of nodes the parser builds from HTML, and the API scripts use to read and change it. Node types: Document, Element (<p>), Text, Comment, DocumentFragment, DocumentType, and ShadowRoot.

Text
<!doctype html>                         Document
<html lang="en">                        ├─ DocumentType (html)
  <head><title>Shop</title></head>      └─ html
  <body>                                    ├─ head
    <h1>Cart</h1>                           │   └─ title ─ #text "Shop"
    <p>3 items</p>                          └─ body
  </body>                                       ├─ #text "\n    "   ← whitespace becomes text nodes!
</html>                                         ├─ h1 ─ #text "Cart"
                                                ├─ #text
                                                └─ p ─ #text "3 items"

Important properties of the DOM:

  • It's live. Changing it changes what's displayed, after the next rendering update (chapter 18).
  • HTML parsing is forgiving: the parser fixes errors according to precise rules instead of failing. <p>a<p>b produces two sibling paragraphs. A <div> inside a <p> closes the paragraph. Tables move stray content outside themselves ("foster parenting"). What you see in DevTools' Elements panel is the parsed DOM, which can differ from your source.
  • Elements vs attributes vs properties: HTML attributes (<input value="a">) initialise DOM properties (input.value), but they aren't the same thing. Typing changes input.value and leaves the value attribute at "a".
  • Shadow DOM attaches a separate, encapsulated tree to an element (<video> controls, web components), with its own styling scope.

The CSSOM

The CSS Object Model is the parsed representation of all stylesheets: rules, selectors and declarations, accessible to scripts through document.styleSheets, CSSStyleSheet, element.style (inline styles) and getComputedStyle(el) (the final resolved values). The browser combines the DOM and CSSOM to compute every property of every element (style resolution), then lays out boxes, paints and composites (chapter 18).

JavaScript
getComputedStyle(document.body).fontSize;   // "16px": the resolved, computed value
const sheet = new CSSStyleSheet();          // constructable stylesheets
sheet.replaceSync(".card { padding: 1rem }");
document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet];

The accessibility tree

From the DOM and computed styles, the browser builds a third tree for assistive technologies: the accessibility tree. Each node has a role (button, link, heading level 2, checkbox), a name (what a screen reader announces), a description, states (checked, expanded, disabled, focused) and relationships. The OS accessibility APIs (UIA on Windows, AX on macOS and iOS, AT-SPI on Linux, Android's accessibility framework) expose it to screen readers, voice control, switch devices and automated testing tools. Playwright's getByRole queries this tree.

Text
DOM:  <button class="btn"><svg …/>Save</button>     → a11y tree: button "Save"
DOM:  <div class="btn" onclick="save()">Save</div>   → a11y tree: generic "Save"  (not a button!)
DOM:  <img src="logo.png">                          → img with no name (screen reader may read the file name)
DOM:  <div style="display:none">…</div>             → nothing (hidden from everyone)

You can inspect it in Chrome DevTools (the Accessibility pane, or the full-tree view) and Firefox's Accessibility Inspector. Chapter 20 is entirely about getting this tree right. Native HTML elements build it correctly for free, which is why semantic HTML matters so much.

The runtime, storage and security

The JavaScript runtime in the page

Each document gets a JavaScript realm: a global object (window), built-in objects (Array, Promise), and its own module map. Page scripts run on the main thread, which is also responsible for style, layout, paint and handling input. Two consequences shape all frontend architecture:

  1. Run-to-completion: a script task runs until it finishes. Nothing else happens on that thread meanwhile: no rendering, no click handling.
  2. Long tasks block the page: any task longer than 50 ms delays input response, and the INP metric (chapter 27) measures exactly that.

The HTML event loop (chapter 15) schedules tasks (events, timers, network callbacks), microtasks (promise callbacks), and rendering opportunities (about 60–120 per second). Other threads exist (Web Workers, the compositor, network and decoding threads) but they can't touch the DOM.

The same JavaScript language also runs outside browsers, with different host APIs: Node.js, Deno and Bun on servers, Cloudflare Workers and other edge runtimes (V8 isolates with Fetch APIs, no Node built-ins), React Native's Hermes, and Electron (Chromium + Node). The WinterTC group (Ecma TC55) standardises the common "server-side web APIs" subset (fetch, Request, Response, URL, streams, crypto.subtle) so code can run across these runtimes.

Storage

Browsers offer several storage mechanisms, all scoped to the origin (and increasingly partitioned by top-level site when embedded cross-site, to stop third-party tracking):

Mechanism API Capacity Persistence Notes
Cookies document.cookie, Set-Cookie, Cookie Store API ~4 KB each, ~50 per domain Session or Expires/Max-Age Sent with every request to matching URLs. Use for sessions, not data
Web Storage localStorage, sessionStorage ~5 MB per origin localStorage until cleared; sessionStorage per tab Synchronous (blocks the main thread), strings only
IndexedDB indexedDB (often via idb or Dexie) Large (a share of disk) Until evicted or cleared Async, transactional, structured clone values, indexes
Cache Storage caches Large Until evicted Request→Response pairs, used by service workers (chapter 29)
Origin Private File System navigator.storage.getDirectory() Large Until evicted Fast file I/O, including sync access handles in workers. SQLite-Wasm runs on it

Storage is best-effort by default: under disk pressure, browsers evict whole origins, least-recently-used first. navigator.storage.persist() requests persistent storage, and navigator.storage.estimate() reports usage and quota. Safari's tracking prevention can delete script-writable storage for sites the user hasn't interacted with for 7 days. Never treat browser storage as the only copy of important data.

The browser security model

The browser runs code from millions of mutually distrustful origins side by side. Its security model has layers:

  1. The same-origin policy (SOP): scripts from origin A can't read origin B's DOM, storage, or (by default) responses. They can still send requests to B, embed B's images and scripts, and submit forms to B, which is the root of CSRF (chapter 28). CORS is how B opts in to letting A read its responses (chapter 19).
  2. Process isolation: site isolation puts each site in its own OS process (chapter 18), so a compromised renderer or a Spectre-style attack (Vol. 1 ch. 7) can't read other sites' memory.
  3. The sandbox: renderer processes run with almost no OS privileges. Files, network and devices go through the browser process, which enforces permissions.
  4. Secure contexts: powerful features (service workers, geolocation, camera, clipboard writes, Web Crypto's subtle, WebAuthn) need HTTPS (or localhost). window.isSecureContext tells you. Mixed content (HTTP subresources on HTTPS pages) is blocked or upgraded.
  5. Permissions: user-granted, per origin, and revocable (camera, notifications, location). The Permissions Policy header controls which features embedded frames may even request.
  6. Opt-in hardening headers that sites send: CSP, X-Frame-Options/frame-ancestors, COOP/COEP/CORP, Trusted Types, HSTS (chapter 28).

Lab: the platform, measured

Every result below came from Chromium 153 (headless, driven by Playwright) talking to small Node servers on localhost. The scripts are short enough to retype; expect your numbers to differ a little, but the shapes to match.

Experiment 1: what each kind of script costs the parser

A Node server delays /slow.js by exactly one second. Five versions of the same page put that script in the <head> in different ways; an inline script after the <h1> records when the parser reached it:

HTML
<head><script src="/slow.js"></script></head>          <!-- or defer, async, type="module", or no script -->
<body><h1 id="h">Heading</h1><script>window.hSeen = performance.now();</script></body>
JavaScript
// /slow.js, served after 1000 ms
window.scriptRan = performance.now(); window.sawHeading = !!document.getElementById('h');
Text
none     heading parsed at    53 ms | DOMContentLoaded    55 ms | script ran   n/a | script saw heading: n/a
classic  heading parsed at  1028 ms | DOMContentLoaded  1029 ms | script ran  1028 ms | script saw heading: false
defer    heading parsed at    13 ms | DOMContentLoaded  1019 ms | script ran  1019 ms | script saw heading: true
async    heading parsed at    16 ms | DOMContentLoaded    18 ms | script ran  1019 ms | script saw heading: true
module   heading parsed at    15 ms | DOMContentLoaded  1019 ms | script ran  1019 ms | script saw heading: true
none classic defer async module 02505007501000 ms parsing to heading slow.js ran DOMContentLoaded
Measured timeline of the five pages. Bars are HTML parsing up to the heading; dots mark when slow.js ran; vertical ticks mark DOMContentLoaded. Only the classic script holds the heading back for a full second

What the numbers say:

  • Classic: the parser stopped at the script for the full second; the heading (and everything after it) wasn't even in the DOM until 1,028 ms, and the script ran before the heading existed (saw heading: false). This is the Start Here chapter's null error, measured.
  • defer and module: parsing finished in about 15 ms; the script downloaded in parallel and ran after parsing, just before DOMContentLoaded, which therefore waited for it. Deferred scripts run in document order; this is the right default for application code.
  • async: parsing finished and DOMContentLoaded fired at 18 ms, without waiting; the script ran whenever it arrived. Async scripts run in arrival order, so use async only for independent scripts (analytics, ads) that nothing else depends on.

Experiment 2: the same-origin policy, observed from both sides

A page on http://localhost:8001 tries to read data from http://localhost:8002. Port 8002 answers /closed with no CORS header and /open with Access-Control-Allow-Origin: http://localhost:8001. The page also embeds an <iframe> from 8002 and tries to read its document:

JavaScript
for (const path of ["/closed", "/open"]) {
  try { const r = await fetch("http://localhost:8002" + path); console.log(path, await r.json()); }
  catch (e) { console.log(path, e.name, e.message); }
}
const f = document.createElement("iframe"); f.src = "http://localhost:8002/frame"; document.body.append(f);
await new Promise(r => f.onload = r);
f.contentWindow.document;      // try to reach into the other origin's page

What the page saw, then what the server on 8002 logged:

Text
/closed: TypeError: Failed to fetch
/open: read {"balance":4200}
contentDocument is null
contentWindow.document: SecurityError: Failed to read a named property 'document' from 'Window':
                        Blocked a frame with origin "http://localhost:8001" from accessing a cross-origin frame.

8002 received GET /closed (Origin: http://localhost:8001)
8002 received GET /open (Origin: http://localhost:8001)
8002 received GET /frame (Origin: -)

Read the server log carefully: the /closed request arrived and was answered. The browser didn't stop the request; it stopped the script from reading the response, and reported it only as an opaque Failed to fetch (deliberately vague, so pages can't probe other origins). Two consequences that the security chapter (28) builds on:

  1. CORS is not a server-side protection. A request that changes something (a POST that transfers money) still reaches the server even when the browser hides the response. That's why CSRF defences are needed.
  2. The Origin header tells the server who's asking, which is how servers make CORS and CSRF decisions.

Experiment 3: storage limits and costs

In the same headless Chromium:

JavaScript
const est = await navigator.storage.estimate();               // quota for this origin
const chunk = "x".repeat(100 * 1024);
try { for (let n = 0; ; n++) localStorage.setItem("k" + n, chunk); }
catch (e) { /* QuotaExceededError */ }
Text
storage.estimate quota: 2048 MB | localStorage filled 5100 KB of 1-byte chars before QuotaExceededError

localStorage stops at about 5 million characters per origin (Chromium counts UTF-16 code units, so that's about 10 MB of memory). The estimate() quota covers IndexedDB, Cache Storage and OPFS, and depends on free disk space and browsing mode: this sandbox's temporary profile reports 2 GB, while a normal profile on a large disk reports far more (Chromium allows an origin up to 60% of the disk). Then the cost and capabilities of each, writing and reading a 2 MB string:

Text
localStorage.setItem  9.80 ms   (synchronous: the page is frozen while it runs)
localStorage.getItem  0.40 ms
IndexedDB put        12.90 ms   (asynchronous: the page keeps running meanwhile)
IndexedDB get        10.10 ms
IndexedDB round-trips Date and Set objects: [true, true]
localStorage.setItem('obj', {a:1}) stores: "[object Object]"

localStorage is fast for small values but blocks the main thread and stores only strings (an object silently becomes "[object Object]"; use JSON.stringify). IndexedDB is asynchronous and stores real objects via the structured clone algorithm (dates, sets, maps, typed arrays, blobs), so it's the right choice for anything large.

Experiment 4: attributes versus properties

JavaScript
document.body.innerHTML = '<input value="a">';
const i = document.querySelector("input");
i.value = "typed";
Text
property: typed | attribute: a | defaultValue: a

The HTML attribute sets the initial value (defaultValue); typing (or setting .value) changes only the property. Form libraries and testing tools that read attributes instead of properties get stale answers; form.reset() restores the attribute value.

Experiment 5: why the back button reloaded the page

The back-forward cache (bfcache) keeps a whole page, JavaScript heap included, in memory when you navigate away, so Back restores it instantly. Chromium reports why it couldn't, through the DevTools protocol (the same reasons appear in DevTools → Application → Back/forward cache):

JavaScript
cdp.on("Page.backForwardCacheNotUsed", e => console.log(e.notRestoredExplanations.map(x => `${x.reason} (${x.type})`)));
Text
/plain
  not used: BrowsingInstanceNotSwapped (Circumstantial), BackForwardCacheDisabledForDelegate (Circumstantial)
/with-unload
  not used: BrowsingInstanceNotSwapped (Circumstantial), BackForwardCacheDisabledForDelegate (Circumstantial), UnloadHandlerExistsInMainFrame (PageSupportNeeded)

The "Circumstantial" reasons come from automation (headless test browsers turn the cache off); in a normal browser /plain would be cached. The page-level blocker is the one you control: UnloadHandlerExistsInMainFrame. Merely registering an unload listener disqualifies the page. Use pagehide or visibilitychange instead; Chrome is removing unload entirely.

Try it yourself

  1. Repeat experiment 1 with two async scripts that take 1,000 ms and 200 ms. Which runs first? Now make both defer. Which runs first now, and why?
  2. In experiment 2, make /closed a POST that increments a counter on the server. Does the counter go up when the page's fetch "fails"? What does that mean for a "transfer money" endpoint?
  3. Open DevTools → Application → Storage on any site you use daily and look at how much each storage type holds. Which sites use IndexedDB, and for what?
  4. Find a site whose Back button feels slow and check its back/forward cache report.

Revision sheet: the web platform

Key ideas

  • The browser is a platform: it runs untrusted code from many origins side by side, isolates them, and exposes capabilities through web APIs.
  • A URL = scheme, host, port, path, query, fragment; build and parse with URL and URLSearchParams, never by string concatenation. The fragment is never sent.
  • An origin = scheme + host + port; a site = scheme + registrable domain (eTLD+1, from the Public Suffix List). Cookies and SameSite work per site; storage and the same-origin policy work per origin.
  • A browsing context / navigable (tab, iframe, popup) hosts one document at a time; navigations create history entries; history.pushState and the Navigation API change the URL without loading a document.
  • Loading: the parser builds the DOM top to bottom; classic scripts block it; defer and modules run after parsing in order; async runs on arrival; CSS blocks rendering (and classic scripts that follow it).
  • Three trees: DOM (content), CSSOM (styles), accessibility tree (what assistive tech sees); rendering combines DOM and CSSOM (chapter 18).
  • The JavaScript runtime in a page: one main thread, an event loop, tasks and microtasks, plus workers for parallelism (chapters 15 and 29).
  • Storage: cookies (sent with requests), Web Storage (sync, strings), IndexedDB (async, structured clone), Cache Storage, OPFS; all best-effort and evictable unless persisted.
  • Security layers: same-origin policy, CORS opt-in, site isolation, the sandbox, secure contexts, permissions, opt-in headers (CSP, COOP/COEP, frame-ancestors, HSTS).
  • Page lifecycle: DOMContentLoaded, load, visibilitychange, pagehide/pageshow, freeze/resume; avoid unload (it blocks the bfcache and is being removed).

Numbers to remember

  • localStorage: about 5 million characters per origin, synchronous.
  • Cookie: about 4 KB each, about 50+ per domain; all matching cookies travel with every request.
  • Chromium quota: the browser up to 80% of disk, one origin up to 60%; Safari may evict script-writable storage after 7 days without user interaction.
  • Default ports: 80 (http), 443 (https), so they're omitted from origins.

Pitfalls

  • Treating localhost and 127.0.0.1 (or www and the apex domain) as the same origin.
  • Expecting CORS to protect a server: the request is still sent and processed.
  • Parser-blocking scripts in the <head>; relying on async scripts' order.
  • Reading attributes when you need live properties (value, checked).
  • Storing objects in localStorage without JSON.stringify.
  • Using unload for saving state (unreliable on mobile, blocks the bfcache); use visibilitychange/pagehide.
  • Keeping the only copy of user data in browser storage.

Glossary

  • eTLD+1: effective top-level domain plus one label (example.co.in), the registrable domain.
  • Navigable: the spec's term for a tab or frame that can navigate between documents.
  • Secure context: a page loaded over HTTPS or from localhost; required for powerful APIs.
  • Opaque origin: an origin that equals nothing, not even itself (file:// pages, sandboxed iframes), serialised as null.
  • Structured clone: the algorithm that copies values for IndexedDB, postMessage and workers.
  • bfcache: the back-forward cache holding whole pages in memory for instant Back/Forward.