DOM and Browser APIs

2005. Google Maps launches. The entire mapping industry is stunned: maps move without a page reload. Under the hood - XMLHttpRequest and intensive DOM manipulation. That moment defined web architecture for the next 20 years.

  • **React Virtual DOM:** abstraction over the DOM API, batch updates and minimal reflows - the reason for its popularity. React DOM diffing saves 10-100x reflow operations on complex UIs
  • **Service Workers + Cache API:** Progressive Web Apps cache fetch requests for offline use. Twitter Lite works on 2G through aggressive caching
  • **ResizeObserver, IntersectionObserver:** modern browser APIs without polling. Infinite scroll, lazy image loading, responsive components - all without setTimeout intervals

Historical context

In 1998, Alex Hopmann at Microsoft built XMLHttpRequest as an ActiveX component for Outlook Web Access - the first corporate webmail. Mozilla shipped a native XHR implementation in 2002. Google then used XHR in Gmail (2004) and Google Maps (2005). Jesse James Garrett coined the term AJAX (Asynchronous JavaScript and XML) in 2005 to describe this pattern. Fetch API arrived in 2015 as XHR's modern replacement. The W3C standardized DOM Level 1 in 1998; the React team invented the Virtual DOM in 2013.

DOM: structure, parsing, and layout reflow

**2004. Gmail launches. For 2004, it is a shock: a web application that behaves like a desktop app - no page reloads.** The secret is JavaScript DOM (Document Object Model) manipulation. The DOM is a tree of objects representing HTML. The browser parses HTML into a DOM tree, applies CSS (CSSOM), merges them into a Render Tree, computes layout (sizes and positions), and paints. Any DOM manipulation potentially restarts this entire cycle.

**Critical Rendering Path:** HTML -> DOM -> CSSOM -> Render Tree -> Layout -> Paint -> Composite. JavaScript blocks HTML parsing (without defer/async). Changing `width` or `display` triggers Layout (expensive). Changing `color` or `opacity` triggers only Paint (cheaper). Animating `transform` or `opacity` via CSS - only Composite (cheap, GPU-accelerated).

Which CSS property is better to animate for smoothness: `left/top` or `transform: translate()`?

Events: bubbling, capturing, and delegation

**Event propagation in the DOM is one of the most common sources of bugs for newcomers.** Clicking a button inside a div fires the event in two phases: capturing (window down to target) and bubbling (target up to window). addEventListener takes a third argument: `true` = capturing phase, `false` (default) = bubbling. This enables intercepting events on parent elements - Event Delegation.

**Memory leaks via event listeners:** if a DOM element is removed but the listener remains - memory leak. Fix: removeEventListener on element removal or use AbortController. React and Vue handle this automatically - the framework manages the lifecycle.

A list of 10,000 elements. Which event handling approach is correct?

Fetch API and async/await: HTTP requests in the browser

**XMLHttpRequest (XHR) - a 1999 API invented by Microsoft for Outlook Web Access.** Callback hell from nested handlers. Fetch API (2015) replaced XHR: Promise-based, clean syntax, async/await support. Since 2022: built into Node.js. Fetch is the standard for browser HTTP requests.

**CORS (Cross-Origin Resource Sharing):** the browser blocks fetch to a different origin (domain, port, protocol). The server must return `Access-Control-Allow-Origin: *` or a specific origin. Preflight: the browser first sends an OPTIONS request for 'unsafe' methods (DELETE, PUT) and custom headers. CORS is a browser protection, not a server one: curl ignores it.

Fetch returns a Response with status 404. Will execution reach the catch block?

Browser storage: cookies, localStorage, IndexedDB

**2009. HTML5 Web Storage API.** Before this, the only way to store data in the browser was cookies (4 KB, sent with every request). localStorage/sessionStorage: 5-10 MB, synchronous, strings only. IndexedDB: gigabytes, async, structured data. Cache API (Service Workers): cache of network responses for offline use.

StorageLimitAsyncSent with requestsUse case
cookie4 KBNoYesAuth tokens, tracking (HttpOnly)
localStorage5-10 MBNoNoUser preferences, app state
sessionStorage5-10 MBNoNoTemporary form data
IndexedDB~1 GB+YesNoOffline data, files, cache
Cache APIFlexibleYesNoService Worker, offline strategies

localStorage is secure for token storage because other domains cannot read it

localStorage is isolated by origin (Same-Origin Policy), but vulnerable to XSS: any JS code on the page (including malicious code from a CDN or via XSS) can read localStorage.

XSS (Cross-Site Scripting) is one of OWASP's top-5 vulnerabilities. If the app has XSS, attackers execute `document.cookie` (without HttpOnly) or `localStorage.getItem('token')`. HttpOnly cookies are inaccessible to JavaScript - that is the key difference. For production: refresh token in HttpOnly cookie + SameSite=Strict.

A JWT access token (short-lived) and refresh token (long-lived) need to be stored in the browser. Where should each go?

DOM and Browser APIs: key ideas

  • DOM manipulation: batch updates via DocumentFragment or innerHTML. Every individual insert triggers a reflow
  • Event bubbling: events propagate from target to document. Event Delegation - one listener on the parent instead of N on children
  • Fetch: Promise-based HTTP. Does not throw on 4xx/5xx - check response.ok explicitly. AbortController for timeouts
  • Storage: localStorage (5MB, synchronous) vs IndexedDB (gigabytes, async). JWT in HttpOnly cookie, not localStorage
  • CSS animation via transform/opacity - GPU composite. left/top - Layout reflow - janky animations

Вопросы для размышления

  • React uses Virtual DOM to optimize DOM mutations. But initializing React costs 200-400 KB of JS and extra parse/execution time. When would direct DOM manipulation without a framework outperform React?

Связанные уроки

  • web-03 — JavaScript fundamentals - the language for working with DOM and browser APIs
  • web-05 — React and Virtual DOM - abstraction over DOM for declarative UI
  • bt-04-dns-tls — Fetch API uses DNS+TLS under the hood for HTTP requests
  • mob-04 — UIKit event handling mirrors DOM events: both implement observer pattern with bubbling
  • devops-04 — Browser cache (localStorage, Cache API) and Docker layer cache share the same idea: avoid recreating what has not changed
  • comp-01-intro
DOM and Browser APIs

0

1

Sign In