DOM Manipulation and Browser APIs Questions
Programming the browser platform directly, without a framework: the Document Object Model, node selection and traversal (live vs static collections), content and attribute mutation (innerHTML vs textContent, attributes vs properties, DocumentFragment, cloning), the event model (capture, target, bubble, delegation, preventDefault vs stopPropagation, passive and once listeners, custom events, pointer, touch and keyboard events, drag and drop), and web-platform APIs (IntersectionObserver, MutationObserver, requestAnimationFrame and requestIdleCallback, Web Storage and IndexedDB and choosing between them, postMessage, BroadcastChannel and cross-tab coordination, fetch error handling with AbortController, Shadow DOM and Web Components). Includes keyboard and screen-reader operable vanilla widgets (modals, dropdowns, accordions, date pickers, carousels, data grids) with focus management and route-change focus, the DOM-level mechanics of reflow and layout thrash, listener and detached-node memory leaks, and writing vanilla JavaScript to build interactive widgets. Ground covered elsewhere: the event loop and promise mechanics, profiling-driven page speed work, form-validation and component-state patterns, application-level security, and rebuilding standard APIs from scratch.
A page must render a list of 500 strings into a ul without janking. Write the function and explain what makes your approach cheaper than appending one node at a time or rewriting innerHTML repeatedly.
Sample Answer
Direct answer
Build the rows off-document and insert them once. Create each <li> with document.createElement, put the text in with document.createTextNode (so a string is never parsed as HTML), collect the rows in a DocumentFragment (a lightweight container that is not part of the page), and hand the fragment to ul.replaceChildren(fragment), which swaps the old rows for the new ones in a single operation.
function renderList(ul, items) {
const frag = document.createDocumentFragment();
for (const text of items) {
const li = document.createElement('li');
li.append(document.createTextNode(String(text))); // text is never parsed as HTML
frag.append(li);
}
ul.replaceChildren(frag); // one insertion; old rows removed
}
What actually makes it cheaper
The popular explanation, "the fragment avoids 500 reflows" (reflow means the browser recomputing element positions and sizes), is not what the measurements below show. The browser does not run layout on every append; it marks the layout dirty (flags it as out of date, to be recomputed later) and does the work once, at the next frame or at the first script read of a layout value. MDN says the same: the performance benefit of DocumentFragment "is often overstated". What the fragment approach does buy:
- One mutation instead of 500. A
MutationObserver(an API that reports DOM changes to script) receives a single record with 500 added nodes, not 500 records. Anything that reacts to DOM changes (observers, accessibility tree updates, other libraries) does the work once. - No chance to interleave a layout read. Any code that reads
offsetHeightorgetBoundingClientRectinside a per-row append loop forces a full layout each time. Building off-document removes that trap. - Rows are created once, never re-parsed.
replaceChildrenalso removes the previous rows and inserts the new ones together, so the list is never visible half-built and a second call is idempotent (calling it again leaves the same 500 rows instead of doubling them).
Column guide for the table: "Observer records" is how many separate batches of changes a MutationObserver delivered, "Nodes added (observer)" is the total number of nodes across those records, and "Layouts (Chromium)" is the change in Chromium's LayoutCount counter (how many times the browser ran a full layout) while the strategy ran. Firefox and WebKit expose no such counter through Playwright, so they are only checked for record and row counts.
The two approaches the question names as slower, compared on the same 500 strings:
| Strategy | Observer records | Nodes added (observer) | Layouts (Chromium) | Notes |
|---|---|---|---|---|
Fragment + replaceChildren | 1 | 500 | 1 | Rows keep identity; text is inert |
ul.append(li) per row | 500 | 500 | 1 | Fine until someone adds a layout read |
ul.append(li) + read offsetHeight per row | 500 | 500 | 500 | Layout thrashing (alternating writes and layout reads so the browser recomputes layout again and again): every read forces layout |
ul.innerHTML += '<li>..' per row | 500 | 125,250 | 1 | Re-serializes and re-parses the whole list every time |
One innerHTML string, assigned once | 1 | 500 | 1 | Fast, but needs escaping (see below) |
The innerHTML += row is the real loser, and it is quadratic: step k serializes the k rows already present to a string, concatenates, and parses them all back into brand-new nodes. For 500 rows the loop re-parsed 2,070,855 characters to produce a list that is 8,390 characters long (about 247 times the final size), and created 1 + 2 + ... + 500 = 125,250 list-item elements to keep 500. Because the old nodes are destroyed, any listener attached to an earlier row is lost and the first row stops being in the document (shown below).
Why not innerHTML for user text
innerHTML runs the HTML parser, so a string such as <img src=x onerror=...> becomes a live element and its handler runs. With createTextNode the same string is displayed literally. The run below calls the same renderList with that string and shows the handler count staying at 0, then assigns it through innerHTML and shows the count reaching 1.
Run all five strategies in three browsers
How the script measures: each strategy is a function kept as a string, so the same harness can inject it into the page with eval(fn) (which turns the string back into a function inside the page) and run it on identical input. Before each run a MutationObserver counts records and added nodes. In Chromium, Performance.getMetrics is read through the DevTools Protocol before and after, and the difference in LayoutCount is the number in the "Layouts" column. The ul.offsetHeight line after the run forces the one final layout that a real page would run before painting, so even the cheap strategies show 1. The two setTimeout waits let pending observer callbacks run before counting.
import { chromium, firefox, webkit } from 'playwright';
import assert from 'node:assert/strict';
const N = 500;
const page_html = '<body><ul id="list"></ul></body>';
// The function under discussion.
const renderList = `
function renderList(ul, items) {
const frag = document.createDocumentFragment();
for (const text of items) {
const li = document.createElement('li');
li.append(document.createTextNode(text)); // text is never parsed as HTML
frag.append(li);
}
ul.replaceChildren(frag); // one insertion, old rows removed
}`;
const strategies = {
'fragment + replaceChildren': `(ul, items) => { ${renderList}; renderList(ul, items); }`,
'append each li directly': `(ul, items) => { for (const t of items) { const li = document.createElement('li'); li.textContent = t; ul.append(li); } }`,
'append + read offsetHeight each time': `(ul, items) => { for (const t of items) { const li = document.createElement('li'); li.textContent = t; ul.append(li); li.offsetHeight; } }`,
'innerHTML += each item': `(ul, items) => { window.__parsed = 0; for (const t of items) { window.__parsed += ul.innerHTML.length; ul.innerHTML += '<li>' + t + '</li>'; } }`,
'one innerHTML string': `(ul, items) => { ul.innerHTML = items.map((t) => '<li>' + t + '</li>').join(''); }`,
};
const rows = {};
for (const type of [chromium, firefox, webkit]) {
const browser = await type.launch();
const page = await browser.newPage();
const cdp = type === chromium ? await page.context().newCDPSession(page) : null;
if (cdp) await cdp.send('Performance.enable');
const layouts = async () => (await cdp.send('Performance.getMetrics')).metrics.find((m) => m.name === 'LayoutCount').value;
for (const [name, fn] of Object.entries(strategies)) {
await page.setContent(page_html);
await page.evaluate(() => {
window.__records = 0; window.__added = 0;
new MutationObserver((rs) => { for (const r of rs) { window.__records++; window.__added += r.addedNodes.length; } })
.observe(document.getElementById('list'), { childList: true });
});
const before = cdp ? await layouts() : null;
const res = await page.evaluate(async ({ fn, N }) => {
const ul = document.getElementById('list');
const items = Array.from({ length: N }, (_, i) => 'item ' + i);
ul.innerHTML = '';
await new Promise((r) => setTimeout(r)); // let the reset's mutation records flush
window.__records = 0; window.__added = 0;
const render = eval(fn);
window.__parsed = null;
render(ul, items);
ul.offsetHeight; // settle: one final layout read
await new Promise((r) => setTimeout(r)); // let MutationObserver callbacks run
return { li: ul.children.length, records: window.__records, added: window.__added,
parsed: window.__parsed ?? null, finalChars: ul.innerHTML.length };
}, { fn, N });
const after = cdp ? await layouts() : null;
rows[name] ??= {};
rows[name][type.name()] = { ...res, layout: cdp ? after - before : null };
}
await browser.close();
}
// Node identity: innerHTML += re-creates every earlier row on each append.
{
const browser = await chromium.launch();
const page = await browser.newPage();
await page.setContent(page_html);
const identity = await page.evaluate(() => {
const ul = document.getElementById('list');
ul.innerHTML = '<li>a</li>';
const kept = ul.firstElementChild;
ul.append(document.createElement('li'));
const viaAppend = kept.isConnected; // append leaves earlier rows alone
ul.innerHTML = '<li>a</li>';
const a = ul.firstElementChild;
ul.innerHTML += '<li>b</li>'; // serialize, concatenate, re-parse everything
return { afterAppend_firstRowStillInDocument: viaAppend, afterInnerHTMLPlusEquals_firstRowStillInDocument: a.isConnected };
});
console.log('identity', JSON.stringify(identity));
// Safety: hostile text.
const hostile = '<img src=x onerror="window.__pwned=(window.__pwned||0)+1">';
const pwned = await page.evaluate(async ({ hostile, renderList }) => {
const render = eval(renderList + '; renderList'); // the same renderList as above
window.__pwned = 0;
const ul = document.getElementById('list');
render(ul, [hostile]);
await new Promise((r) => setTimeout(r, 300));
const textSafe = { pwned: window.__pwned, shown: ul.textContent };
ul.innerHTML = '<li>' + hostile + '</li>';
await new Promise((r) => setTimeout(r, 300));
return { textSafe, innerHTML: window.__pwned };
}, { hostile, renderList });
console.log('hostile', JSON.stringify(pwned));
assert.equal(pwned.textSafe.pwned, 0);
assert.equal(pwned.textSafe.shown, hostile); // the previous rows were replaced, not kept
assert.ok(pwned.innerHTML >= 1);
// Idempotence: a second call replaces the rows instead of doubling them.
const twice = await page.evaluate(({ renderList }) => {
const render = eval(renderList + '; renderList');
const ul = document.getElementById('list');
const items = Array.from({ length: 500 }, (_, i) => 'item ' + i);
render(ul, items);
render(ul, items);
return ul.children.length;
}, { renderList });
console.log('renderList called twice: li=' + twice);
assert.equal(twice, 500);
await browser.close();
}
for (const [name, byBrowser] of Object.entries(rows)) {
const c = byBrowser.chromium;
console.log(`${name.padEnd(38)} li=${c.li} observerRecords=${c.records} nodesAdded=${c.added} layouts(chromium)=${c.layout}` +
(c.parsed !== null ? ` charsReparsed=${c.parsed} finalChars=${c.finalChars}` : ''));
for (const b of ['firefox', 'webkit']) {
assert.equal(byBrowser[b].records, c.records, `${name}: ${b} record count differs`);
assert.equal(byBrowser[b].li, N);
}
}
Run in the Playwright 1.48.2 image, with the layout counts read from Chromium's Performance.getMetrics LayoutCount through the DevTools protocol, it prints:
identity {"afterAppend_firstRowStillInDocument":true,"afterInnerHTMLPlusEquals_firstRowStillInDocument":false}
hostile {"textSafe":{"pwned":0,"shown":"<img src=x onerror=\"window.__pwned=(window.__pwned||0)+1\">"},"innerHTML":1}
renderList called twice: li=500
fragment + replaceChildren li=500 observerRecords=1 nodesAdded=500 layouts(chromium)=1
append each li directly li=500 observerRecords=500 nodesAdded=500 layouts(chromium)=1
append + read offsetHeight each time li=500 observerRecords=500 nodesAdded=500 layouts(chromium)=500
innerHTML += each item li=500 observerRecords=500 nodesAdded=125250 layouts(chromium)=1 charsReparsed=2070855 finalChars=8390
one innerHTML string li=500 observerRecords=1 nodesAdded=500 layouts(chromium)=1
The script fails if Firefox or WebKit report a different observer record count or row count than Chromium, or if renderList lets the hostile string run (swapping its createTextNode for innerHTML makes the assert fail), or if calling renderList twice leaves more than 500 rows (swapping replaceChildren for append makes the assert fail). Repeated runs print identical lines because every figure is a count, not a time.
Beyond 500 rows, and other details
- Many more rows. Past a few thousand rows the cost is rendering and memory, not insertion, so the answer changes. Three levers address different costs:
content-visibility: autoon the rows is a CSS property that lets the browser skip layout and painting for rows that are off screen (one line of CSS); rendering in chunks across frames withrequestAnimationFrame(a function that runs your callback just before the next screen refresh) keeps the page responsive while the rows are being inserted; and virtualizing (keeping only the rows currently in view in the DOM, and swapping them as the user scrolls) also bounds memory. Start with the CSS property, add chunking if inserting still freezes the page, and virtualize when the list reaches tens of thousands of rows or memory is the problem. - Rows with structure. Put the row markup in a
<template>and calltemplate.content.cloneNode(true)per item, then fill in text withtextContent. This stays inert and avoids hand-builtcreateElementchains. - Events. Attach one click listener to the
uland useevent.target.closest('li')(event delegation) rather than 500 listeners. - Edge cases. An empty
itemsarray makesreplaceChildren(emptyFragment)clear the list. Non-string values go throughString(...). CallingrenderListagain replaces rather than appends. - Complexity. Building and inserting is O(n) in the number of rows;
innerHTML +=per row is O(n^2) in characters parsed.
Running the code
# package.json must contain {"type":"module"}; save the listing as render-list.mjs
docker run --rm -v "$PWD":/w -w /w mcr.microsoft.com/playwright:v1.48.2-jammy \
sh -c "npm i playwright@1.48.2 && node render-list.mjs"
A search box handles typing with input, change, and several keyboard events in different places and behaves inconsistently. Explain how those events differ, when each fires, and what to watch for when handling high-frequency ones.
Sample Answer
Direct answer
The events answer different questions. input fires after every change the user makes to the field's value (typing, deleting, pasting, cutting, drag and drop, autofill, IME), and the new value is already readable. It does not fire when script assigns input.value = ...: with an input listener attached, the script value= step of the harness below logs no events at all in Chromium, Firefox and WebKit. change fires when the user commits the value: for a text box that is when it loses focus after being edited, and in the three engines tested also when Enter is pressed. keydown fires when a key goes down, before the character is inserted, so input.value is still the old text. keyup fires when the key is released, after the value has changed. keypress is deprecated: MDN tells you to use beforeinput (an event that fires just before the browser changes the field's value, and can be cancelled) or keydown instead. A search box that reads value in keydown handlers lags one character behind, one that listens to change only searches on blur or Enter, and one that mixes them can run the same search more than once per keystroke. The fix is a single input listener, debounced (it waits until the user pauses typing before searching), that skips text that is still being composed (a character an input method editor is still assembling from several keystrokes, as when typing Chinese, Japanese or Korean) and cancels the request that is already in flight (sent to the server, with no response back yet) using an AbortController (a built-in object whose signal lets you cancel a fetch).
When each fires
The harness attaches a listener for every event type to one text input and records the order, with input.value at the moments that matter, for each action. The page is driven by Playwright in Chromium, Firefox and WebKit (the engine, not Safari). The last line uses the Chrome DevTools Protocol (CDP, the command channel Playwright uses to drive Chromium below the level of ordinary key presses) to simulate an IME (input method editor, the software that composes a character like 你 from typed letters such as ni; only Chromium exposes that here). In that run, Input.imeSetComposition plays the role of the user typing ni while the IME holds it as provisional text, and Input.insertText plays the user choosing 你.
// input_events.mjs
import { chromium, firefox, webkit } from 'playwright';
const html = `<input id="q" type="text">`;
const watch = () => {
window.log = [];
const q = document.getElementById('q');
for (const t of ['keydown', 'keypress', 'beforeinput', 'compositionstart', 'compositionupdate', 'compositionend', 'input', 'change', 'keyup']) {
q.addEventListener(t, (e) => {
const flag = t === 'input' ? `(${e.inputType}${e.isComposing ? ',composing' : ''})` : t.startsWith('key') ? `(${e.key})` : '';
const seen = ['keydown', 'input', 'keyup'].includes(t) ? `[value="${q.value}"]` : ''; // what input.value holds right now
window.log.push(t + flag + seen);
});
}
const mark = (s) => () => window.log.push(s);
q.addEventListener('blur', mark('--blur--'));
};
for (const [name, type] of Object.entries({ chromium, firefox, webkit })) {
const browser = await type.launch();
const page = await browser.newPage();
await page.setContent(html);
await page.evaluate(watch);
const step = async (label, fn) => {
await page.evaluate(() => { window.log = []; });
await fn();
console.log(name.padEnd(8), label.padEnd(16), ((await page.evaluate(() => window.log)).join(' ') || '(no events)'));
};
await page.focus('#q');
await step('type "a"', () => page.keyboard.press('a'));
await step('Backspace', () => page.keyboard.press('Backspace'));
await step('type "b"', () => page.keyboard.press('b'));
await step('blur()', () => page.evaluate(() => document.getElementById('q').blur()));
await step('refocus + "z"', async () => { await page.focus('#q'); await page.keyboard.press('z'); });
await step('Enter', () => page.keyboard.press('Enter'));
await step('script value=', () => page.evaluate(() => { document.getElementById('q').value = 'set by script'; }));
await browser.close();
}
// IME composition, driven through the DevTools protocol (Chromium).
{
const browser = await chromium.launch();
const page = await browser.newPage();
await page.setContent(html);
await page.evaluate(watch);
await page.focus('#q');
const cdp = await page.context().newCDPSession(page);
await cdp.send('Input.imeSetComposition', { text: 'ni', selectionStart: 2, selectionEnd: 2 });
await cdp.send('Input.insertText', { text: '你' });
console.log('chromium IME ', (await page.evaluate(() => window.log)).join(' '));
await browser.close();
}
chromium type "a" keydown(a)[value=""] keypress(a) beforeinput input(insertText)[value="a"] keyup(a)[value="a"]
chromium Backspace keydown(Backspace)[value="a"] beforeinput input(deleteContentBackward)[value=""] keyup(Backspace)[value=""]
chromium type "b" keydown(b)[value=""] keypress(b) beforeinput input(insertText)[value="b"] keyup(b)[value="b"]
chromium blur() change --blur--
chromium refocus + "z" keydown(z)[value="b"] keypress(z) beforeinput input(insertText)[value="bz"] keyup(z)[value="bz"]
chromium Enter keydown(Enter)[value="bz"] keypress(Enter) beforeinput change keyup(Enter)[value="bz"]
chromium script value= (no events)
firefox type "a" keydown(a)[value=""] keypress(a) beforeinput input(insertText)[value="a"] keyup(a)[value="a"]
firefox Backspace keydown(Backspace)[value="a"] beforeinput input(deleteContentBackward)[value=""] keyup(Backspace)[value=""]
firefox type "b" keydown(b)[value=""] keypress(b) beforeinput input(insertText)[value="b"] keyup(b)[value="b"]
firefox blur() change --blur--
firefox refocus + "z" keydown(z)[value="b"] keypress(z) beforeinput input(insertText)[value="bz"] keyup(z)[value="bz"]
firefox Enter keydown(Enter)[value="bz"] keypress(Enter) beforeinput change keyup(Enter)[value="bz"]
firefox script value= (no events)
webkit type "a" keydown(a)[value=""] keypress(a) beforeinput input(insertText)[value="a"] keyup(a)[value="a"]
webkit Backspace keydown(Backspace)[value="a"] beforeinput input(deleteContentBackward)[value=""] keyup(Backspace)[value=""]
webkit type "b" keydown(b)[value=""] keypress(b) beforeinput input(insertText)[value="b"] keyup(b)[value="b"]
webkit blur() change --blur--
webkit refocus + "z" keydown(z)[value="b"] keypress(z) beforeinput input(insertText)[value="bz"] keyup(z)[value="bz"]
webkit Enter keydown(Enter)[value="bz"] keypress(Enter) change keyup(Enter)[value="bz"]
webkit script value= (no events)
chromium IME compositionstart compositionupdate beforeinput input(insertCompositionText,composing)[value="ni"] compositionupdate beforeinput input(insertCompositionText,composing)[value="你"] compositionend
What the output shows, per action:
- A character key.
keydown(value still empty),keypress,beforeinput,input(value nowa),keyup. In all three engines. - Backspace. The same without
keypress, andinputreportsinputTypedeleteContentBackward. TheinputTypefield tells you which kind of edit happened. - Script assignment. Setting
input.value = 'set by script'logs nothing: noinput, nochange, no key event, in all three engines. - Blur after typing.
changefires once, and before theblurlistener runs, in all three engines. Nothing fires forchangeon each key. - Enter. In Chromium and Firefox the sequence is
keydown(Enter),keypress(Enter),beforeinput,change,keyup(Enter); WebKit prints the same withoutbeforeinput.changefires in all three here because the value had been edited since it was last committed. - IME composition.
compositionstart,compositionupdate,beforeinput, theninputwithisComposingtrue (printed ascomposing) while the value isni, then the committed你, thencompositionend. The value changed twice and neither change was final text untilcompositionend.
Which one to use for what
- Reading the current text:
input. It is the only one of these that runs after every user edit, whatever the source (keyboard, paste, drag and drop, autofill), with the new value in place. A script assignment tovaluefires nothing, so code that clears or fills the box itself must call the search directly or dispatch aninputevent. - Shortcuts and navigation (Enter to submit, Escape to clear, arrows to move through suggestions):
keydown. Useevent.key, andevent.preventDefault()here when you want to stop the default action. - Commit semantics (save a field when the user is done editing):
change. - Avoid
keypress. Deprecated, and it does not fire for Backspace, as the output shows.
A search box that does not misbehave
The harness below types ab, waits for the debounced search to start, types c while that request is still in flight, and checks that the first request is cancelled and its response never reaches the page. A fake fetch with an abort signal stands in for the network. It then drives the same page through an IME composition in Chromium: it holds the composition open for 500 ms, longer than the 250 ms debounce, checks that no search has started for the provisional ni, and only then commits 你.
// search_box.mjs
import { chromium, firefox, webkit } from 'playwright';
import assert from 'node:assert/strict';
const html = `<input id="q"><div id="out"></div>`;
// Page code: debounce the input event, skip IME composition, abort the stale request.
const pageCode = `
const input = document.getElementById('q'), out = document.getElementById('out');
let timer, controller;
window.calls = [];
window.renders = [];
async function search(term) {
controller?.abort(); // cancel the previous in-flight request
controller = new AbortController();
window.calls.push(term);
try {
const results = await fakeFetch(term, controller.signal);
out.textContent = 'results for ' + results;
window.renders.push(results);
} catch (err) { if (err.name !== 'AbortError') throw err; }
}
function fakeFetch(term, signal) { // stands in for fetch(url, { signal })
return new Promise((resolve, reject) => {
const t = setTimeout(() => resolve(term), 400);
signal.addEventListener('abort', () => { clearTimeout(t); reject(new DOMException('aborted', 'AbortError')); });
});
}
const schedule = () => {
clearTimeout(timer);
timer = setTimeout(() => search(input.value.trim()), 250);
};
input.addEventListener('input', (e) => { if (!e.isComposing) schedule(); }); // skip half-typed IME text
input.addEventListener('compositionend', schedule); // search the committed text`;
for (const [name, type] of Object.entries({ chromium, firefox, webkit })) {
const browser = await type.launch();
const page = await browser.newPage();
await page.setContent(html);
await page.addScriptTag({ content: pageCode });
await page.focus('#q');
await page.keyboard.type('ab', { delay: 30 }); // one debounced search for "ab"
await page.waitForFunction(() => window.calls.length === 1);
await page.keyboard.type('c'); // while "ab" is in flight (400 ms fetch)
await page.waitForFunction(() => document.getElementById('out').textContent === 'results for abc');
const calls = await page.evaluate(() => window.calls);
const renders = await page.evaluate(() => window.renders);
assert.deepEqual(calls, ['ab', 'abc']);
assert.deepEqual(renders, ['abc']); // the response for "ab" was cancelled and never painted
console.log(name, 'searches:', JSON.stringify(calls), '| rendered:', JSON.stringify(renders));
await browser.close();
}
{ // IME composition in Chromium: only the committed text is searched
const browser = await chromium.launch();
const page = await browser.newPage();
await page.setContent(html);
await page.addScriptTag({ content: pageCode });
await page.focus('#q');
const cdp = await page.context().newCDPSession(page);
await cdp.send('Input.imeSetComposition', { text: 'ni', selectionStart: 2, selectionEnd: 2 });
await page.waitForTimeout(500); // longer than the 250 ms debounce, composition still open
assert.deepEqual(await page.evaluate(() => window.calls), []); // "ni" was never searched
await cdp.send('Input.insertText', { text: '\u4f60' });
await page.waitForFunction(() => document.getElementById('out').textContent.startsWith('results for'));
const calls = await page.evaluate(() => window.calls);
assert.deepEqual(calls, ['\u4f60']);
console.log('chromium IME searches:', JSON.stringify(calls));
await browser.close();
}
chromium searches: ["ab","abc"] | rendered: ["abc"]
firefox searches: ["ab","abc"] | rendered: ["abc"]
webkit searches: ["ab","abc"] | rendered: ["abc"]
chromium IME searches: ["你"]
The page logged searches for ab and abc only (the debounce collapsed the two key presses of ab into one search and abc aborted ab), and it painted only abc. In the composition run nothing is searched while ni is provisional, even after the debounce interval has passed, and the only search is for the committed character 你. Deleting the isComposing check makes that run fail with a search for ni.
High-frequency pitfalls
- Debounce before doing the work. A debounce waits until events stop for a set time (250 ms here) before running. It is the right default for search. A throttle runs at most once per interval, however many events arrive, which suits continuous events such as
scroll. - Cancel stale requests. A stale request is one whose answer is already out of date because the user has typed more since. The responses of two requests can arrive in the opposite order to their start.
AbortControllercancels the older one; the page above shows the older response never painted. - Composition. While
isComposingis true the text is provisional. Skip it, then search oncompositionend, as the code does. - Trim and compare. Skip a search when the trimmed value equals the last searched value, for example after a keystroke that did not change the text.
- Do not read
valueinkeydown. It is the text from before the key press, which is the reason a "search as you type" built on key events lags by one character.
Running the code
mkdir demo && cd demo
echo '{"type":"module"}' > package.json
npm i playwright@1.48.2
npx playwright install chromium firefox webkit
# save the listing(s) above as input_events.mjs, search_box.mjs, then run:
node input_events.mjs
node search_box.mjs
The printed output comes from runs in the mcr.microsoft.com/playwright:v1.48.2-jammy container, where the browsers are already installed and the install step is not needed. Playwright's WebKit build is the WebKit engine, not Safari itself.
Users submit actions while offline, such as form submissions and interaction events, and these must reach the server later without loss, duplication, or reordering. Design the client-side queue: where it lives, how it survives reloads, and how it retries.
Sample Answer
Direct answer
Persist every action in IndexedDB (the browser's asynchronous, transactional database) in an outbox store before trying to send it, give it a client-generated idempotency key (a unique ID the server uses to recognise a repeat), and drain the outbox with one sequential loop that deletes an entry only after the server acknowledges it. The three guarantees come from three different places:
- No loss: write to the outbox first, delete only after an acknowledgement. A crash, reload or dropped connection leaves the entry in place.
- No duplication: delivery is "at least once" (every action is sent one or more times, never zero, so duplicates are possible and the server must ignore repeats) because the client cannot know whether a request that failed in flight was applied. The server removes the duplicates by storing results per idempotency key and answering a repeat with the stored answer.
- No reordering: the outbox key is an auto-incrementing sequence number and the loop sends the head entry, waits for the outcome, and only then looks at the next. On a retryable failure it stops and retries the same head later.
Design
| Question | Choice | Why |
|---|---|---|
| Where does it live | IndexedDB object store outbox with autoIncrement key | Survives reloads and crashes, stores structured data and blobs, asynchronous. localStorage is synchronous, string-only and has no transactions, so a half-written queue is possible |
| What is stored | { seq, id (UUID), payload, createdAt, attempts } | seq fixes order; id is sent as the Idempotency-Key header; attempts drives backoff |
| Enqueue | add in a transaction, wait for the transaction to complete, then trigger a drain | The UI can show success as soon as the write is durable |
| Drain | One loop: read lowest seq, POST, then act on the outcome | Sequential sending is what preserves order |
| Success (2xx) | Delete the entry | Only now is it safe to forget |
| Network error or timeout | Keep, increase attempts, retry with exponential backoff and jitter | The outcome is unknown: the server may have applied it. Same id makes the retry safe |
| 408 (request timeout), 429 (too many requests), 5xx (server error) | Keep the head (the oldest entry, first in line; stopping on it so later ones cannot overtake is called head-of-line blocking), back off | Server trouble; skipping ahead would reorder |
| Other 4xx | Move to a dead store (a dead-letter store: where permanently rejected actions are parked for a human) in the same transaction (a group of reads and writes that all succeed or all fail together) as the delete | Repeating the same request cannot succeed; do not block everything behind it, and let the user see or fix it |
| Triggers | Startup, the online event, a backoff timer, each enqueue | navigator.onLine only hints: MDN calls it inherently unreliable (a computer connected to a LAN counts as online even without Internet access) and says not to disable features based on it, so the loop learns about the network from fetch failing |
| Several tabs | navigator.locks.request(name, { ifAvailable: true }, ...) | Web Locks (navigator.locks, a browser API for named locks) are shared by all tabs and workers of one origin (MDN), so only one tab drains at a time |
Backoff with jitter means each retry waits a random time between half of and the full min(max, base * 2^attempts). Jitter stops many devices that reconnect together from hitting the server in the same instant. With baseDelayMs = 1000 and maxDelayMs = 60000 the code's ceiling is min(60000, 1000 * 2^attempts) and the actual wait is a random value from half the ceiling up to the ceiling:
attempts | Ceiling | Wait range |
|---|---|---|
| 0 | 1 s | 0.5 s to 1 s |
| 1 | 2 s | 1 s to 2 s |
| 2 | 4 s | 2 s to 4 s |
| 3 | 8 s | 4 s to 8 s |
| 4 | 16 s | 8 s to 16 s |
| 5 | 32 s | 16 s to 32 s |
| 6 or more | 60 s (cap; 2^6 x 1 s = 64 s would exceed it) | 30 s to 60 s |
The queue and its tests
The two small adapters at the top of the file turn IndexedDB's callback style into promises. IndexedDB does not return promises: every operation returns a request object whose onsuccess or onerror fires later. wrap(req) resolves with req.result when the request succeeds, and done(tx) resolves when a whole transaction commits (oncomplete), so await done(tx) means the data is durably stored. onupgradeneeded runs once when the database is first created (or its version number rises) and is the only place object stores can be created. A cursor walks the records of a store in key order; openCursor() followed by cursor.value reads the first, lowest-seq record, or the request yields null when the store is empty, so head() returns the oldest queued action or null. In loop, for (let record = await head(); record; record = await head()) therefore means: take the oldest action, process it, and ask again for the oldest remaining one, stopping when none is left. Deleting an acknowledged record is what makes the next head() return the next action, and a return on failure leaves the same record at the head for the next attempt.
// offline-queue.js: durable, ordered, retrying outbox backed by IndexedDB.
const DB_NAME = 'offline-queue';
const wrap = (req) => new Promise((resolve, reject) => { req.onsuccess = () => resolve(req.result); req.onerror = () => reject(req.error); });
const done = (tx) => new Promise((resolve, reject) => { tx.oncomplete = () => resolve(); tx.onerror = tx.onabort = () => reject(tx.error); });
function openDb() {
const req = indexedDB.open(DB_NAME, 1);
req.onupgradeneeded = () => {
req.result.createObjectStore('outbox', { keyPath: 'seq', autoIncrement: true }); // seq = insertion order
req.result.createObjectStore('dead', { keyPath: 'seq' }); // actions the server rejected for good
};
return wrap(req);
}
export function createQueue({ endpoint, baseDelayMs = 1000, maxDelayMs = 60000, timeoutMs = 10000 } = {}) {
const dbPromise = openDb();
let retryTimer = null;
async function enqueue(payload) {
const db = await dbPromise;
const record = { id: crypto.randomUUID(), payload, createdAt: Date.now(), attempts: 0 }; // id doubles as the idempotency key
const tx = db.transaction('outbox', 'readwrite');
tx.objectStore('outbox').add(record);
await done(tx); // only now is the action safe; then try to send
drain();
return record.id;
}
async function head() {
const db = await dbPromise;
const cursor = await wrap(db.transaction('outbox').objectStore('outbox').openCursor()); // lowest seq first
return cursor ? cursor.value : null;
}
async function settle(record, outcome) { // delete (acked) or move to dead letters, in ONE transaction
const db = await dbPromise;
const tx = db.transaction(['outbox', 'dead'], 'readwrite');
tx.objectStore('outbox').delete(record.seq);
if (outcome === 'dead') tx.objectStore('dead').put(record);
await done(tx);
}
async function bumpAttempts(record) {
const db = await dbPromise;
const tx = db.transaction('outbox', 'readwrite');
tx.objectStore('outbox').put({ ...record, attempts: record.attempts + 1 });
await done(tx);
}
function scheduleRetry(attempts) {
clearTimeout(retryTimer);
const ceiling = Math.min(maxDelayMs, baseDelayMs * 2 ** attempts);
retryTimer = setTimeout(drain, ceiling * (0.5 + Math.random() / 2)); // exponential backoff with jitter
}
async function loop() {
for (let record = await head(); record; record = await head()) {
let response;
try {
response = await fetch(endpoint, {
method: 'POST',
headers: { 'content-type': 'application/json', 'Idempotency-Key': record.id },
body: JSON.stringify(record.payload),
signal: AbortSignal.timeout(timeoutMs),
});
} catch { // offline, DNS failure, reset connection, timeout: outcome unknown
await bumpAttempts(record);
return scheduleRetry(record.attempts);
}
if (response.ok) { await settle(record, 'ack'); continue; }
if (response.status === 408 || response.status === 429 || response.status >= 500) {
await bumpAttempts(record); // server trouble: keep the head, keep the order, back off
return scheduleRetry(record.attempts);
}
await settle(record, 'dead'); // 4xx: retrying the same request cannot succeed
}
}
// One drainer at a time across ALL tabs of this origin: the lock is held only while this tab is draining.
function drain() {
return navigator.locks.request('offline-queue-drain', { ifAvailable: true }, (lock) => (lock ? loop() : undefined));
}
addEventListener('online', drain);
drain(); // on startup: whatever survived the last session
return {
enqueue,
drain,
async size() { return (await wrap((await dbPromise).transaction('outbox').objectStore('outbox').count())); },
async deadLetters() { return (await wrap((await dbPromise).transaction('dead').objectStore('dead').getAll())).map((r) => r.payload); },
};
}
The test uses a fake server that applies each action once per Idempotency-Key and injects five faults: action 1 gets a 429 once, for action 2 it applies the action and then never answers (the response is lost, so the client's timeout fires), action 3 is rejected with 400, action 4 gets a 503 once, and action 5 gets no answer at all once, so the client's 300 ms timeout must fire. Network loss is simulated by aborting every request to /actions in Playwright, and the page is reloaded while "offline" to prove persistence.
// queue-test.mjs
import http from 'node:http';
import fs from 'node:fs';
import { chromium } from 'playwright';
// ---- Fake server: dedupes by Idempotency-Key and injects faults. ----
const processed = []; // payload.n in the order the server APPLIED them
const byKey = new Map(); // Idempotency-Key -> response body
const seen = { replays: 0, lostResponses: 0, unavailable: 0, throttled: 0, hung: 0 };
// action 1: 429 once; action 2: applied but the response is lost; action 3: 400; action 4: 503 once; action 5: no answer once (client timeout)
const faults = { loseResponseFor: 2, unavailableFor: 4, throttleFor: 1, hangFor: 5 }; // first attempt only
const firstAttempt = new Set();
const server = http.createServer((req, res) => {
if (req.method === 'GET') {
const body = req.url === '/queue.js' ? fs.readFileSync('offline-queue.js') : '<!doctype html><title>app</title>';
return res.writeHead(200, { 'content-type': req.url === '/queue.js' ? 'text/javascript' : 'text/html' }).end(body);
}
let raw = '';
req.on('data', (c) => (raw += c));
req.on('end', () => {
const key = req.headers['idempotency-key'];
const payload = JSON.parse(raw);
if (byKey.has(key)) { seen.replays++; return res.writeHead(200).end(byKey.get(key)); } // replay: same answer, no second effect
if (payload.bad) return res.writeHead(400).end('rejected');
if (payload.n === faults.unavailableFor && !firstAttempt.has('u')) { firstAttempt.add('u'); seen.unavailable++; return res.writeHead(503).end(); }
if (payload.n === faults.throttleFor && !firstAttempt.has('t')) { firstAttempt.add('t'); seen.throttled++; return res.writeHead(429).end(); }
if (payload.n === faults.hangFor && !firstAttempt.has('h')) { firstAttempt.add('h'); seen.hung++; return; } // never answers: the client's timeout must fire
processed.push(payload.n); // the effect happens exactly once per key
byKey.set(key, JSON.stringify({ ok: true, n: payload.n }));
if (payload.n === faults.loseResponseFor && !firstAttempt.has('l')) { firstAttempt.add('l'); seen.lostResponses++; return; } // applied, but the response never arrives: the client's timeout fires
res.writeHead(200).end(byKey.get(key));
});
});
await new Promise((r) => server.listen(0, '127.0.0.1', r));
const origin = `http://127.0.0.1:${server.address().port}`;
let failures = 0;
const check = (label, ok, extra = '') => { if (!ok) failures++; console.log(` ${ok ? 'PASS' : 'FAIL'} ${label} ${extra}`); };
const sleepUntil = async (cond, ms = 15000) => { const t = Date.now(); while (!(await cond())) { if (Date.now() - t > ms) throw new Error('timed out waiting for condition'); await new Promise((r) => setTimeout(r, 25)); } };
const browser = await chromium.launch();
const ctx = await browser.newContext();
const boot = (page) => page.evaluate(async (origin) => {
const { createQueue } = await import('/queue.js');
window.q = createQueue({ endpoint: origin + '/actions', baseDelayMs: 40, maxDelayMs: 200, timeoutMs: 300 });
}, origin);
const offline = (page) => page.route('**/actions', (r) => r.abort('internetdisconnected')); // every request fails at the network level
// ---- Scenario 1: offline writes survive a reload, then drain in order with lost response, 503 and a rejected action. ----
console.log('scenario 1: offline, reload, reconnect');
const page = await ctx.newPage();
await page.goto(origin + '/');
await offline(page);
await boot(page);
for (const payload of [{ n: 1 }, { n: 2 }, { n: 3, bad: true }, { n: 4 }, { n: 5 }]) await page.evaluate((p) => q.enqueue(p), payload);
check('offline: all 5 actions held, server saw none', await page.evaluate(() => q.size()) === 5 && processed.length === 0);
await page.reload(); // a fresh JavaScript context: nothing in memory
await offline(page);
await boot(page);
check('after reload: the 5 actions are still queued (IndexedDB)', await page.evaluate(() => q.size()) === 5);
await page.unroute('**/actions'); // network is back
await page.evaluate(() => dispatchEvent(new Event('online')));
await sleepUntil(async () => (await page.evaluate(() => q.size())) === 0);
check('server applied 1, 2, 4, 5 in order, each exactly once', JSON.stringify(processed) === '[1,2,4,5]', JSON.stringify(processed));
check('lost response for 2 was retried and answered from the server\'s idempotency record', seen.lostResponses === 1 && seen.replays === 1, JSON.stringify(seen));
check('503 for 4 was retried', seen.unavailable === 1);
check('429 for 1 and a request that never answers (5) were retried', seen.throttled === 1 && seen.hung === 1, JSON.stringify(seen));
check('rejected action 3 is in dead letters, not retried forever', JSON.stringify(await page.evaluate(() => q.deadLetters())) === '[{"n":3,"bad":true}]');
// ---- Scenario 2: two tabs draining the same outbox. ----
console.log('scenario 2: two tabs');
processed.length = 0; seen.replays = 0;
const tabA = page, tabB = await ctx.newPage();
await tabB.goto(origin + '/');
await offline(tabA); await boot(tabB); await offline(tabB);
for (let n = 11; n <= 18; n++) await tabA.evaluate((p) => q.enqueue(p), { n });
await tabA.unroute('**/actions'); await tabB.unroute('**/actions');
await Promise.all([tabA.evaluate(() => q.drain()), tabB.evaluate(() => q.drain())]); // both try at the same moment
await sleepUntil(async () => (await tabA.evaluate(() => q.size())) === 0);
check('both tabs drained concurrently: 11..18 applied in order, once each', JSON.stringify(processed) === JSON.stringify([11, 12, 13, 14, 15, 16, 17, 18]), JSON.stringify(processed));
check('no key was sent twice (the lock admitted one drainer)', seen.replays === 0);
await browser.close();
server.close();
console.log(failures ? failures + ' CHECK(S) FAILED' : 'ALL CHECKS PASSED');
process.exit(failures ? 1 : 0);
Output (identical on 10 consecutive runs; run in Chromium):
scenario 1: offline, reload, reconnect
PASS offline: all 5 actions held, server saw none
PASS after reload: the 5 actions are still queued (IndexedDB)
PASS server applied 1, 2, 4, 5 in order, each exactly once [1,2,4,5]
PASS lost response for 2 was retried and answered from the server's idempotency record {"replays":1,"lostResponses":1,"unavailable":1,"throttled":1,"hung":1}
PASS 503 for 4 was retried
PASS 429 for 1 and a request that never answers (5) were retried {"replays":1,"lostResponses":1,"unavailable":1,"throttled":1,"hung":1}
PASS rejected action 3 is in dead letters, not retried forever
scenario 2: two tabs
PASS both tabs drained concurrently: 11..18 applied in order, once each [11,12,13,14,15,16,17,18]
PASS no key was sent twice (the lock admitted one drainer)
ALL CHECKS PASSED
What it shows:
- Five actions made while offline are still queued after a reload, and the server had received none of them.
- After reconnecting, the server applies 1, 2, 4, 5 in that order, each once. Action 2's lost response (the server applied it and never answered, so the client timed out) caused a retry with the same key and the server answered from its record instead of applying it again. Simulating the loss by destroying the socket does not test this: Chromium itself replays a POST whose reused connection was reset, with the same headers, so the queue sees no failure and a new key per attempt would go unnoticed. Action 4's 503 was retried before action 5 was sent. Action 1's 429 and action 5's missing answer (a client-side timeout) were also kept at the head and retried, so nothing behind them overtook them.
- The rejected action 3 sits in the dead-letter store with its payload instead of being retried forever.
- Two tabs calling
drain()at the same moment still produce 11 to 18 in order with no key sent twice. With thenavigator.locks.request(...)call indrainreplaced by a plainreturn loop();, the same test run in Chromium failsno key was sent twice (the lock admitted one drainer)every time, while both order checks still pass: concurrent drainers send the same head entry twice, and the server's idempotency record keeps the applied order correct. Without the lock, the enqueue,onlineand retry-timer triggers also start overlapping loops inside a single tab, so in some runs the replay count checked in scenario 1 is off as well and the run ends with2 CHECK(S) FAILEDinstead of1 CHECK(S) FAILED. That is why both mechanisms are needed.
Failure modes and trade-offs
- Idempotency needs the server's cooperation. If the API cannot dedupe by key, the client cannot promise "no duplication"; the only fallback is a server-side natural key (for example a client-generated order ID that the database treats as unique).
- Ordering across unrelated actions is a choice. One global head-of-line queue is the simplest correct design. If actions on different documents are independent, partition by document ID and run one loop per partition so one stuck document does not block the rest.
- Dead letters need a UI. Silent discarding is data loss. Show the user the rejected actions and let them retry or drop them.
- Storage is best-effort by default. Browsers can evict an origin's data under storage pressure, and MDN documents
navigator.storage.persist()to request persistent storage, which the browser may grant or deny. Writes can also throwQuotaExceededError(the error raised when the browser's storage allowance for the origin is full); catch it inenqueueand tell the user the action was not saved. - A tab that does not get the lock does nothing until its next trigger. Startup,
onlineand enqueue all trigger a drain; add a slow periodic tick if a tab may sit idle while another tab owning the lock closes. - Background Sync (a service worker, a script the browser runs in the background for a site even when its pages are closed, receives a
syncevent when connectivity returns) can run the same drain with the page closed, but MDN marks it "Limited availability" (not Baseline, because it does not work in some widely used browsers), so treat it as an enhancement over the page-level loop, not a replacement. - Auth expiry: treat 401 as "pause the queue and ask the user to sign in", not as a dead letter; the actions are still valid. The listing above does not do this: its last line sends every 4xx other than 408 and 429, including 401, to the dead letters. Add a branch before that line, for example
if (response.status === 401) { onAuthNeeded(); return; }(stop draining without scheduling a retry, and calldrain()again after sign-in), so an expired token does not discard valid actions. - Schema changes: the queue lives across app versions, so version the object store (
onupgradeneeded) and store the payload's schema version.
Running the code
mkdir demo && cd demo && mkdir oq && echo '{"type":"module"}' > package.json
npm i playwright@1.48.2
# save the two listings as oq/offline-queue.js and oq/queue-test.mjs
docker run --rm -v "$PWD":/w -w /w/oq mcr.microsoft.com/playwright:v1.48.2-jammy node queue-test.mjs
Exit code 0 means every check passed. The fake server runs inside the test process; nothing else needs to be started.
Given the following HTML:
<ul id="menu"> <li class="item" data-id="1">Home</li> <li class="item" data-id="2">About</li> <li class="item" data-id="3">Contact</li> </ul>Write three JavaScript statements that: (1) select the <ul> by id, (2) select all <li> elements as a NodeList, and (3) select the second <li> using a CSS selector. After the code, briefly explain when you would prefer querySelector/querySelectorAll over getElementById/getElementsByClassName in real code.
Sample Answer
Direct answer
const menu = document.getElementById('menu'); // (1) the <ul>
const items = document.querySelectorAll('#menu li'); // (2) every <li>, as a NodeList
const second = document.querySelector('#menu li:nth-child(2)'); // (3) the second <li> ("About")
querySelector and querySelectorAll take any CSS selector, so the same string you would write in a stylesheet (or in a Playwright or Selenium locator, the lookup call test-automation tools use to find an element) works. getElementById and getElementsByClassName take only a bare name. Prefer the querySelector pair when the question is about structure or attributes, one API covers everything, and the result is a static snapshot (a list that keeps the elements found at that moment and does not change when the page changes later). Keep getElementById for a plain id lookup, and use getElementsByClassName only when you want a live view (a collection the browser keeps up to date as matching elements are added or removed).
Run it
// select_three.mjs
import { chromium, firefox, webkit } from 'playwright';
import assert from 'node:assert/strict';
const html = `<ul id="menu">
<li class="item" data-id="1">Home</li>
<li class="item" data-id="2">About</li>
<li class="item" data-id="3">Contact</li>
</ul>`;
for (const [name, type] of Object.entries({ chromium, firefox, webkit })) {
const browser = await type.launch();
const page = await browser.newPage();
await page.setContent(html);
const r = await page.evaluate(() => {
const menu = document.getElementById('menu'); // (1) the <ul>
const items = document.querySelectorAll('#menu li'); // (2) all <li> as a NodeList
const second = document.querySelector('#menu li:nth-child(2)'); // (3) second <li>
return {
menu: menu.tagName, items: items.length, kind: items.constructor.name,
second: second.textContent, secondByData: document.querySelector('li[data-id="2"]').textContent,
missing: document.querySelector('.nope'), emptyList: document.querySelectorAll('.nope').length,
sameAsClassName: document.getElementsByClassName('item')[1] === second,
};
});
console.log(name, JSON.stringify(r));
assert.deepEqual([r.menu, r.items, r.kind, r.second], ['UL', 3, 'NodeList', 'About']);
assert.equal(r.missing, null);
assert.equal(r.emptyList, 0);
assert.ok(r.sameAsClassName);
await browser.close();
}
Output (Chromium; Firefox and WebKit print the same values):
chromium {"menu":"UL","items":3,"kind":"NodeList","second":"About","secondByData":"About","missing":null,"emptyList":0,"sameAsClassName":true}
menu is the UL; the NodeList has 3 entries; the second item's text is About. li[data-id="2"] selects the same element by attribute, and getElementsByClassName('item')[1] is the identical node (sameAsClassName: true).
Static versus live, and escaping an id
// static_vs_live.mjs
import { chromium, firefox, webkit } from 'playwright';
import assert from 'node:assert/strict';
const html = `<ul id="menu">
<li class="item" data-id="1">Home</li>
<li class="item" data-id="2">About</li>
<li class="item" data-id="3">Contact</li>
</ul>`;
for (const [name, type] of Object.entries({ chromium, firefox, webkit })) {
const browser = await type.launch();
const page = await browser.newPage();
await page.setContent(html);
const r = await page.evaluate(() => {
const snapshot = document.querySelectorAll('.item'); // static NodeList
const live = document.getElementsByClassName('item'); // live HTMLCollection
const before = [snapshot.length, live.length];
const li = document.createElement('li');
li.className = 'item';
document.getElementById('menu').append(li);
const after = [snapshot.length, live.length];
let bad = null;
try { document.querySelector('#1st'); } catch (e) { bad = e.name; }
const id = '1st';
return { before, after, bad, escaped: CSS.escape(id), fixed: document.querySelector('#' + CSS.escape(id)) };
});
console.log(name, JSON.stringify(r));
assert.deepEqual(r.before, [3, 3]);
assert.deepEqual(r.after, [3, 4]);
assert.equal(r.bad, 'SyntaxError');
assert.equal(r.escaped, '\\31 st');
assert.equal(r.fixed, null);
await browser.close();
}
Output (Chromium; Firefox and WebKit print the same values):
chromium {"before":[3,3],"after":[3,4],"bad":"SyntaxError","escaped":"\\31 st","fixed":null}
After one <li class="item"> is appended, the querySelectorAll NodeList still has 3 entries and the live getElementsByClassName collection has 4. The unescaped #1st throws a SyntaxError; the escaped selector parses and returns null because no element has that id. (The \\31 st in the JSON output is the 6-character string \31 st, backslash included.)
When to use which
| Need | Use | Why |
|---|---|---|
| Element with a known id | getElementById('menu') | Direct lookup, no selector syntax to get wrong; an id with odd characters needs no escaping |
Nested or attribute-based match (#menu li[data-id="2"], :nth-child(2)) | querySelector | getElementsBy* cannot express it |
| All matches, then loop and modify | querySelectorAll | Static NodeList with forEach, safe to mutate while looping |
| Zero matches | either querySelector (gives null) or querySelectorAll (gives an empty NodeList) | Check null before using the single result; the run shows missing: null, emptyList: 0 |
| A view that follows later DOM changes | getElementsByClassName | Live HTMLCollection |
Details that trip people
:nth-child(2)counts every child element position, regardless of tag or class; whitespace text between the<li>tags does not count.:nth-of-typecounts among siblings of the same tag.- A selector string that is invalid throws a
SyntaxError(MDN). A CSS identifier cannot start with a digit, sodocument.querySelector('#1st')throws;CSS.escape('1st')returns\31 st, which makes'#' + CSS.escape(id)a valid selector for any id, including one typed by a user. The section above runs both. NodeListhasforEachbut notmap; wrap withArray.fromwhen you need array methods.- Selecting by
data-attributes ([data-id="2"]) is more stable than by position when items can be reordered.
Running the code
mkdir demo && cd demo
echo '{"type":"module"}' > package.json # save the listings as select_three.mjs and static_vs_live.mjs here
docker run --rm -v "$PWD":/w -w /w mcr.microsoft.com/playwright:v1.48.2-jammy \
sh -c 'npm i playwright@1.48.2 && node select_three.mjs && node static_vs_live.mjs'
The image ships Chromium, Firefox and WebKit, so one run covers all three. The listing ends with assert calls, so a browser that disagrees makes the script exit with an error.
Write a small browser helper that loads the user list from GET /api/users and returns the parsed data. Callers need to tell a server error response apart from the network being down, with the status where there is one. Walk me through what fetch does and does not treat as a failure.
Sample Answer
fetch only rejects when it gets no HTTP response at all. A 404 or 500 is a successful round trip as far as fetch is concerned, so the promise resolves and you must check response.ok (true for statuses 200 to 299) or response.status yourself. MDN: "A fetch() promise only rejects when the request fails, for example, because of a badly-formed request URL or a network error. A fetch() promise does not reject if the server responds with HTTP status codes that indicate errors (404, 504, etc.)." The helper below turns that into three error classes callers can tell apart: HttpError (the server answered, with a status), NetworkError (no answer), and ParseError (the server said success but the body is not JSON), plus the caller's own AbortError passed through untouched. A caller then branches on the class and status, for example if (err.name === 'HttpError' && err.status === 401) showLogin(), else if (err.name === 'NetworkError') showOfflineBanner(), and a ParseError is reported as a server bug.
What fetch does and does not treat as a failure
| Situation | What fetch does | Helper result |
|---|---|---|
| 200 with a JSON body | resolves, ok is true | returns parsed data |
| 404, 500 or any other non-2xx | resolves, ok is false | throws HttpError with status and the start of the body |
| Connection reset, DNS failure, offline, request blocked by CORS (the browser's cross-origin rule) | rejects with a TypeError | throws NetworkError, status is null |
| Server never answers, or sends headers and then stalls mid-body | waits until aborted | AbortSignal.timeout fires, helper throws NetworkError |
| 200 with an empty body or an HTML login page | resolves, ok is true | response.json() rejects, helper throws ParseError carrying status 200 |
Caller calls abort() on its own signal | rejects with AbortError | rethrown as is, because a cancel is not a failure to report |
Two details matter in interviews. First, a TypeError from fetch is deliberately vague: the browser does not tell a script whether the cause was offline, DNS, a reset or a CORS block, so the helper cannot either. Second, a successful status does not mean usable data: proxies and captive portals (the sign-in pages that hotel or airport Wi-Fi serves in place of the real site) often answer 200 with HTML, and response.json() is what exposes it, so the parse step needs its own error class.
Implementation
// users.js
export class HttpError extends Error {
constructor(status, statusText, body) {
super(`HTTP ${status} ${statusText}`.trim());
this.name = 'HttpError';
this.status = status; // the server answered; callers branch on this
this.body = body;
}
}
export class NetworkError extends Error {
constructor(message, cause) {
super(message, { cause });
this.name = 'NetworkError'; // no HTTP response at all: offline, DNS, reset, CORS block, timeout
this.status = null;
}
}
export class ParseError extends Error {
constructor(status, cause) {
super('Response body is not valid JSON', { cause });
this.name = 'ParseError';
this.status = status; // the server answered 2xx but the body was unusable
}
}
export async function loadUsers({ url = '/api/users', signal, timeoutMs = 5000 } = {}) {
const timeout = AbortSignal.timeout(timeoutMs);
const combined = signal ? AbortSignal.any([signal, timeout]) : timeout;
let res;
try {
res = await fetch(url, { headers: { Accept: 'application/json' }, signal: combined });
} catch (err) {
if (signal?.aborted) throw err; // the caller cancelled: not a failure to report
if (err.name === 'TimeoutError') throw new NetworkError(`No response within ${timeoutMs} ms`, err);
throw new NetworkError('Network request failed', err); // fetch rejects with a TypeError here
}
if (!res.ok) { // 4xx and 5xx still resolve; ok is status 200-299
const body = await res.text().catch(() => '');
throw new HttpError(res.status, res.statusText, body.slice(0, 500));
}
try {
return await res.json(); // rejects on an empty or non-JSON body
} catch (err) {
if (combined.aborted && !signal?.aborted) throw new NetworkError(`Body not finished within ${timeoutMs} ms`, err);
if (signal?.aborted) throw err;
throw new ParseError(res.status, err);
}
}
Choices worth defending:
- Custom error classes with a
nameand astatusfield let callers branch witherr.name === 'HttpError' && err.status === 401rather than parsing message text. - Timeout plus caller cancel. An abort signal is the object
fetchwatches in order to cancel a request.AbortSignal.timeout(ms)makes a signal that aborts by itself after the delay, with aDOMExceptionnamedTimeoutErroras its reason (MDN);AbortSignal.any([...])makes one signal that aborts when any of the listed signals does, here the caller's signal or the timeout. When a request is cancelledfetchrejects with the aborting signal's reason, so a timeout reaches the helper asTimeoutErrorand a caller's plainabort()asAbortError, which is why the two names differ. The helper checkssignal?.abortedfirst so a user cancel is never relabelled as a network problem. - Body read inside the same guard. A connection can drop after the headers arrive, in which case
res.json()rejects with a network-level error, not malformed JSON. The helper checks whether the timeout caused it before calling it aParseError. The three checks in the secondcatchmap like this:combined.abortedtrue and the caller'ssignalnot aborted means the timeout fired while the body was still arriving, soNetworkError; the caller'ssignalaborted means the caller cancelled, so the error is rethrown as is (AbortError); neither aborted means the bytes arrived in full and were not JSON, soParseError. The order matters, because a caller cancel also setscombined.aborted, and the first test excludes it. - Error body kept short.
body.slice(0, 500)gives support staff the server's message ({"error":"no such route"}) without holding a large page in memory. 204 No Content. This endpoint always returns a list, so an empty body is treated as a broken response. For an endpoint that may legitimately answer 204, testres.status === 204before callingres.json().
Test
The harness starts a small Node HTTP server with one route per case and runs the helper in real Chromium, Firefox and WebKit pages through Playwright. The "network down" cases are a route that destroys the socket and a route that never answers, which are reproducible; unplugging the network is not. In the page script, the aborted case starts its request first (the call runs synchronously as far as issuing the fetch), then ctl.abort() cancels it while it is still hanging, and the result is awaited last so the other cases run in between without affecting it; starting it after abort() would test an already-cancelled signal instead of an in-flight request. A further case cancels a request after the headers arrived, while the body is still streaming, and a final check reads HttpError.body for a short message and for a 5,000-character page that must be cut to 500 characters. Every normal response carries Connection: close, so no request reuses a socket left over from an earlier case that destroyed or abandoned its connection; without that header the last check failed occasionally in WebKit under load, and with it the failures stopped.
// users-test.mjs
import { chromium, firefox, webkit } from 'playwright';
import { readFileSync } from 'node:fs';
import http from 'node:http';
import assert from 'node:assert/strict';
const lib = readFileSync('users.js', 'utf8').replace(/export /g, '');
const server = http.createServer((req, res) => {
const send = (code, type, body) => { res.writeHead(code, { 'Content-Type': type, Connection: 'close' }); res.end(body); }; // no connection reuse between cases
switch (req.url) {
case '/': return send(200, 'text/html', '<!doctype html><title>t</title>');
case '/api/users': return send(200, 'application/json', '[{"id":1,"name":"Ada"}]');
case '/api/missing': return send(404, 'application/json', '{"error":"no such route"}');
case '/api/boom': return send(500, 'text/plain', 'upstream exploded');
case '/api/empty': return send(200, 'application/json', '');
case '/api/login-page': return send(200, 'text/html', '<html>sign in</html>');
case '/api/huge': return send(500, 'text/plain', 'x'.repeat(5000));
case '/api/drop': return req.socket.destroy(); // connection reset: fetch has no response to resolve with
case '/api/hang': return; // never answers
case '/api/slow-body': res.writeHead(200, { 'Content-Type': 'application/json' }); return res.write('[{"id":'); // headers and half a body, then silence
}
});
await new Promise((r) => server.listen(0, '127.0.0.1', r));
const origin = `http://127.0.0.1:${server.address().port}`;
for (const [name, type] of Object.entries({ chromium, firefox, webkit })) {
const browser = await type.launch();
const page = await browser.newPage();
await page.goto(origin + '/');
await page.addScriptTag({ content: lib });
const outcome = await page.evaluate(async () => {
const run = async (label, opts) => {
try { const d = await loadUsers(opts); return `${label}: data ${JSON.stringify(d)}`; }
catch (e) { return `${label}: ${e.name} status=${e.status ?? 'none'}`; }
};
const ctl = new AbortController();
const aborted = run('aborted', { url: '/api/hang', signal: ctl.signal });
ctl.abort();
const ctl2 = new AbortController(); // cancelled after the headers arrived, while the body is still streaming
const midBody = run('cancel-mid-body', { url: '/api/slow-body', signal: ctl2.signal });
setTimeout(() => ctl2.abort(), 300);
return [
await run('ok', {}),
await run('404', { url: '/api/missing' }),
await run('500', { url: '/api/boom' }),
await run('empty', { url: '/api/empty' }),
await run('html', { url: '/api/login-page' }),
await run('reset', { url: '/api/drop' }),
await run('timeout', { url: '/api/hang', timeoutMs: 200 }),
await run('slow-body', { url: '/api/slow-body', timeoutMs: 200 }),
await midBody,
await aborted,
];
});
assert.deepEqual(outcome, [
'ok: data [{"id":1,"name":"Ada"}]',
'404: HttpError status=404',
'500: HttpError status=500',
'empty: ParseError status=200',
'html: ParseError status=200',
'reset: NetworkError status=none',
'timeout: NetworkError status=none',
'slow-body: NetworkError status=none',
'cancel-mid-body: AbortError status=none',
'aborted: AbortError status=none',
]);
// the error carries the start of the server's message, cut to 500 characters
const bodies = await page.evaluate(async () => {
const body = (url) => loadUsers({ url }).catch((e) => e.body);
return [await body('/api/missing'), (await body('/api/huge')).length];
});
assert.deepEqual(bodies, ['{"error":"no such route"}', 500]);
if (name === 'chromium') console.log(outcome.join('\n'));
console.log(name, 'ok');
await browser.close();
}
server.close();
Re-run many times, including with several containers at once, the test passed in all three engines. Deleting the signal?.aborted rethrow in the body catch, or the slice(0, 500), makes the run fail. The lines the Chromium page printed (the other two matched the same assertion list):
ok: data [{"id":1,"name":"Ada"}]
404: HttpError status=404
500: HttpError status=500
empty: ParseError status=200
html: ParseError status=200
reset: NetworkError status=none
timeout: NetworkError status=none
slow-body: NetworkError status=none
cancel-mid-body: AbortError status=none
aborted: AbortError status=none
chromium ok
Complexity and edge cases
One request and one body read: O(n) in the size of the response, constant extra memory apart from the parsed value. Edge cases the helper handles: non-JSON success bodies, empty bodies, a hung server, a caller cancelling, and a body that fails mid-stream. It does not retry; retries belong in the caller because only the caller knows whether the request is safe to repeat (a GET is, a payment POST is not).
Running the code
npm init -y && npm pkg set type=module
npm i playwright@1.48.2
npx playwright install chromium firefox webkit
node users-test.mjs
Save the listings as users.js and users-test.mjs in one folder. The script prints the lines shown above for Chromium, then firefox ok and webkit ok.
Unlock Full Question Bank
Get access to all 30 DOM Manipulation and Browser APIs interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.