Advanced · 10 of 11 · 15 min read
Web APIs
The browser's own capabilities — workers, sockets, storage, observers and fetch — and the line between them and the language.
- Web APIs
setTimeout, fetch, localStorage and the DOM are not JavaScript. The language specifies
syntax, types and the event loop’s semantics; everything that talks to the outside world is
provided by the host — the browser, or Node with its own different set.
Language or platform
| In the language | A Web API |
|---|---|
Array, Object, Map, Promise |
fetch, XMLHttpRequest |
JSON, Math, Date, Intl |
document, the whole DOM |
async / await, the microtask queue |
setTimeout, setInterval |
Symbol, Proxy, Reflect |
localStorage, IndexedDB |
globalThis |
window, navigator, location |
console.log(typeof Promise); // "function" — the language, everywhere
console.log(typeof setTimeout); // "function" — the host, in both browser and Node
console.log(typeof document); // "undefined" in Node — browser only
Code meant for both has to feature-detect rather than assume:
const canStore = typeof localStorage !== 'undefined';
console.log(typeof canStore); // "boolean"
Web Workers
A worker runs a script on a separate thread, so a long computation does not block rendering, clicks or timers.
// worker.js
self.addEventListener('message', (event) => {
const result = heavy(event.data); // takes two seconds, and nobody notices
self.postMessage(result);
});
function heavy(n) {
let total = 0;
for (let i = 0; i < n; i++) total += i;
return total;
}
// main.js
const worker = new Worker('./worker.js', { type: 'module' });
worker.addEventListener('message', (event) => {
console.log('result:', event.data); // arrives without the page having frozen
});
worker.postMessage(1e9);
// The page stays responsive the whole time.
worker.terminate(); // when you are done — workers are not free
What a worker cannot do is the part people get wrong:
// Inside a worker:
// document.querySelector('#x'); // ReferenceError — there is no DOM
// window.alert('hi'); // no window either
// `self`, fetch, WebSocket, IndexedDB and postMessage are available
So the shape is always: main thread owns the DOM, worker owns the computation, and they exchange messages. Messages are copied with the structured clone algorithm, not shared:
const data = { big: new Array(1000).fill(0) };
worker.postMessage(data); // copied — functions and DOM nodes would throw
// To move instead of copy, for a large buffer:
const buffer = new ArrayBuffer(1024);
worker.postMessage(buffer, [buffer]); // transferred
console.log(buffer.byteLength); // 0 — this side no longer owns it
Use one when the work is genuinely CPU-bound — parsing a huge file, image processing, crypto. For
waiting on the network you do not need a worker: fetch is already asynchronous.
WebSockets
HTTP is request/response: the client asks, the server answers, the connection closes. A WebSocket is one connection that stays open and lets either side send at any time.
const socket = new WebSocket('wss://example.com/live');
socket.addEventListener('open', () => socket.send(JSON.stringify({ subscribe: 'prices' })));
socket.addEventListener('message', (event) => console.log('pushed:', event.data));
socket.addEventListener('close', (event) => console.log('closed', event.code));
socket.addEventListener('error', () => console.log('connection failed'));
// socket.close();
Polling with fetch |
WebSocket | |
|---|---|---|
| Who can start a message | the client only | either side |
| Connection | new per request | one, kept open |
| Latency to a server event | up to the poll interval | immediate |
| Overhead per message | full HTTP headers | a couple of bytes |
| Works through every proxy | yes | usually, not always |
| Reconnection | nothing to do | you must handle it |
That last row is the real cost. A socket drops — a sleeping laptop, a changed network — and nothing tells your code to reconnect. Production code needs a backoff loop and a heartbeat.
When the data only flows server to client, Server-Sent Events are simpler and reconnect automatically:
const events = new EventSource('/stream');
events.addEventListener('message', (e) => console.log(e.data));
// Built-in retry, plain HTTP, but one direction only.
Storage
localStorage.setItem('theme', 'dark'); // strings only, survives restarts
console.log(localStorage.getItem('theme')); // "dark"
localStorage.removeItem('theme');
sessionStorage.setItem('draft', 'hello'); // cleared when the tab closes
// Objects have to be serialised, and parsing has to be defended
localStorage.setItem('user', JSON.stringify({ id: 1 }));
try {
console.log(JSON.parse(localStorage.getItem('user') ?? 'null')); // { id: 1 }
} catch {
console.log('corrupt value'); // someone edited it, or it was truncated
}
localStorage |
sessionStorage |
Cookies | IndexedDB | |
|---|---|---|---|---|
| Lifetime | until cleared | the tab | an expiry you set | until cleared |
| Size | ~5 MB | ~5 MB | ~4 KB | large |
| Sent to the server | no | no | on every request | no |
| API | synchronous | synchronous | synchronous | asynchronous |
| Stores objects | strings only | strings only | strings only | yes |
Two things to say about localStorage in an interview: it is synchronous, so a big read blocks
the thread; and every access can throw — private mode, blocked site data, a full quota — so it
belongs in a try/catch.
function readSetting(key) {
try {
return localStorage.getItem(key);
} catch {
return null; // storage can be unavailable; the page must still work
}
}
Observers
Four APIs that replaced the scroll-and-resize listeners that used to burn frames. They are callback-based, batched by the browser, and run off the main work:
// Is this element on screen? — lazy images, infinite scroll, analytics
const io = new IntersectionObserver((entries) => {
for (const entry of entries) if (entry.isIntersecting) console.log('visible');
});
// io.observe(element);
// Did this element change size? — better than a window resize listener
const ro = new ResizeObserver((entries) => console.log(entries[0]?.contentRect.width));
// Did the DOM change? — reacting to markup you do not control
const mo = new MutationObserver((records) => console.log(records.length, 'changes'));
// How fast was it? — real user metrics
const po = new PerformanceObserver((list) => console.log(list.getEntries().length));
IntersectionObserver is the one worth knowing by name: “how would you lazy-load images or build
an infinite scroll?” has it as the answer, and the old version of that answer — a scroll listener
calling getBoundingClientRect — forces a layout on every frame.
Fetch, and cancelling
const controller = new AbortController();
const promise = fetch('/api/slow', { signal: controller.signal })
.then((response) => {
if (!response.ok) throw new Error(`HTTP ${response.status}`); // fetch does NOT throw on 404
return response.json();
})
.catch((error) => {
if (error.name === 'AbortError') return console.log('cancelled');
throw error;
});
controller.abort(); // the request stops, the promise rejects with AbortError
The trap is in the comment: fetch only rejects on a network failure. A 404 or a 500 resolves
normally with response.ok === false, which is why every wrapper starts by checking it.
The same signal also removes event listeners, which makes cleanup one call:
const c = new AbortController();
// element.addEventListener('click', onClick, { signal: c.signal });
// element.addEventListener('keydown', onKey, { signal: c.signal });
c.abort(); // both listeners gone
Common mistakes
Expecting fetch to reject on an error status
Mistake. try { await fetch(url) } catch { /* handle 500 */ }.
Why it fails. A 500 is a successful HTTP exchange as far as fetch is concerned; only a
network failure rejects.
What to do instead. Check response.ok and throw yourself.
Reaching for a worker to speed up network calls
Mistake. Moving fetch into a Web Worker to “not block the UI”.
Why it fails. fetch never blocked the UI — waiting happens off-thread already. You added
message passing and a second script for nothing.
What to do instead. Workers for CPU-bound work. For I/O, plain async/await.
Treating localStorage as always available
Mistake. JSON.parse(localStorage.getItem('user')).name.
Why it fails. Three ways to crash in one line: the accessor can throw in private mode,
getItem returns null when absent, and the stored text can be corrupt.
What to do instead. Wrap access in try/catch, default the null, and parse defensively.
Check yourself
2 questions from the bank on what you just read. Answering here does not affect your quiz history.
What does a Web Worker give you?
What does a WebSocket give you that repeated HTTP requests do not?
Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.