Web Platform & APIs: SDE-3 Reference
This section covers the browser environment, exploring how HTML is parsed and rendered, how network streams are handled, and how multi-threading is achieved.
12. DOM and Layout Trees
The browser's rendering engine processes HTML, styles, and scripts to display pixels on screen.
The Critical Rendering Path (CRP)
- DOM Tree: Built by parsing HTML tokens into nested nodes.
- CSSOM Tree: Built by parsing CSS rules.
- Render Tree: Combines DOM and CSSOM. Nodes with
display: noneare omitted. - Layout (Reflow): Computes the exact geometry (size and position) of each visible node relative to the viewport.
- Paint: Converts the Render Tree into paint records (lists of draw commands like line drawings, rectangles, shadows).
- Compositing: Splitting elements into GPU layers (e.g. elements with
transform,will-change) and drawing them to the screen in a separate compositor thread.
Layout Thrashing (Reflow Loop)
Layout Thrashing occurs when code repeatedly reads layout properties (which forces the browser to calculate layout synchronously) followed by layout-modifying writes.
// BAD: Layout Thrashing (forces layout calculation every loop iteration)
for (let i = 0; i < elements.length; i++) {
const width = elements[i].offsetWidth; // Read (Forced Synced Layout)
elements[i].style.height = (width * 2) + "px"; // Write (Invalidates layout)
}
// GOOD: Batch reads, then batch writes
const widths = elements.map(el => el.offsetWidth); // Batch Read
elements.forEach((el, idx) => {
el.style.height = (widths[idx] * 2) + "px"; // Batch Write
});13. Fetch API
The fetch() method is a modern promise-based interface to make HTTP requests, replacing XMLHttpRequest.
Core Architecture & Response Streaming
fetch() resolves as soon as the HTTP headers are received. The actual response body is a ReadableStream, allowing the browser to parse chunked payloads before they are completely downloaded, reducing the memory footprint.
async function consumeStream(url) {
const response = await fetch(url);
const reader = response.body.getReader();
let receivedLength = 0;
while (true) {
const { done, value } = await reader.read();
if (done) break;
receivedLength += value.length;
console.log(`Received chunk of size ${value.length}. Total: ${receivedLength}`);
}
}AbortController & Cancellation
Unlike standard Promises which cannot be cancelled once initialized, Fetch uses the AbortController to cancel active HTTP operations.
const controller = new AbortController();
const signal = controller.signal;
// Make fetch request passing the abort signal
fetch("https://api.example.com/data", { signal })
.then(res => res.json())
.catch(err => {
if (err.name === 'AbortError') {
console.log('Fetch request was successfully aborted.');
} else {
console.error('Fetch failed:', err);
}
});
// Cancel the request
controller.abort();14. Web Workers
JavaScript is single-threaded, running on the browser's UI thread. Web Workers run scripts in a separate background thread, isolated from the window, DOM, and local layout trees.
Communications & Transferable Objects
Workers communicate with the main thread via postMessage(). By default, data is copied via the Structured Clone Algorithm, which can cause a CPU bottleneck if cloning large structures (e.g. 100MB arrays).
To bypass this, Transferable Objects (like ArrayBuffer, MessagePort, or ImageBitmap) transfer ownership of the underlying memory directly to the worker thread without copying (zero-copy memory transfer). The main thread can no longer access the object after transfer.
// Main Thread
const worker = new Worker('worker.js');
// Allocate 32MB of raw memory
const buffer = new ArrayBuffer(32 * 1024 * 1024);
// Transfer ownership of buffer to worker. Zero cloning overhead!
worker.postMessage({ buffer }, [buffer]);
console.log(buffer.byteLength); // 0 (Ownership transferred, now inaccessible on main thread)
// worker.js (Background Thread)
self.onmessage = function(e) {
const { buffer } = e.data;
console.log(`Worker received buffer size: ${buffer.byteLength}`); // 33554432 (32MB)
};Mark this page when you finish learning it.
Spotted something unclear or wrong on this page?