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.
Implement, in vanilla JavaScript, an event delegation handler attached to a container with id 'list' that handles clicks on child elements bearing a data-action attribute. The handler should dispatch to different functions based on data-action, support elements added dynamically, avoid expensive DOM queries on each click, and correctly handle events originating from nested child nodes.
Sample Answer
Direct answer
Attach one click listener to #list. When a click arrives, event.target.closest('[data-action]') climbs from the exact node that was hit (an icon, a text span) to the nearest ancestor that declares an action. Read dataset.action from that element and look the name up in an object that maps action names to functions (a dispatch table: the name picks the function, so there is no growing if/else chain), then call the match with the element and the event. This handles nested children because closest starts at the target and walks up, handles dynamic elements because the listener is on the stable container and resolves the element at click time (event delegation, where one parent listener serves many children), and avoids expensive DOM queries because the work per click is one ancestor walk plus one property lookup. No querySelector, no per-item listener, no scan of the list.
The handler
function installActions(container, handlers) {
const onClick = (event) => {
const el = event.target.closest('[data-action]');
if (!el || !container.contains(el)) return;
const fn = Object.hasOwn(handlers, el.dataset.action) && handlers[el.dataset.action];
if (typeof fn === 'function') fn(el, event);
};
container.addEventListener('click', onClick);
return () => container.removeEventListener('click', onClick);
}
Each guard answers a specific failure:
closest('[data-action]')runs from the clicked node upward, so a click on<i>inside<span class="icon">inside the button still finds the button. Readingevent.target.dataset.actiondirectly would beundefinedthere.container.contains(el)rejects a match that sits above the container. In the test below an outer wrapper hasdata-action="outer-trap"; without this check, a click on plain text in the list would climb to the wrapper and fire an action the list never owned.Object.hasOwn(handlers, name)returns true only for keys the table defines itself, not keys inherited from its prototype. Every ordinary object inherits members such asconstructorandtoStringfromObject.prototype(the shared parent object that plain objects fall back to when a key is missing). Markup withdata-action="constructor"or"toString"would otherwise find those inherited functions and call them. The guard is enough on its own; aMapor an object created withObject.create(null)(no parent at all) avoids the same trap if you prefer a table that cannot inherit anything.typeof fn === 'function'ignores unknown action names quietly instead of throwing on a click.
Test in three engines
The harness counts calls to querySelector and querySelectorAll after installation, clicks a nested icon, adds a button after registration and clicks it, then clicks the "constructor" button, a button whose action name is not in the table, and a plain paragraph, while collecting pageerror events. Its dispatch table is built so that the two traps are observable: it inherits a constructor function that records inherited-constructor if anything calls it, and it has an own outer-trap action that records outer-trap if the wrapper's action is ever reached. Deleting Object.hasOwn therefore adds inherited-constructor to the result, and deleting container.contains(el) adds outer-trap; either makes the deepEqual fail, and deleting the typeof fn === 'function' check makes the unknown-action click throw inside the page, which fails the final errors assertion. To count the calls, the injected script replaces (monkey-patches) each of those four methods, on Element.prototype and Document.prototype, with a wrapper that adds one to window.queries and then calls the original method. If the delegated click path ever ran a selector query, the counter would rise above zero and the final assert.equal(queries, 0) would fail. The remaining scaffolding (exposeFunction to report back to Node, toString() to ship the function into the page) is the usual harness plumbing, not part of the solution.
// delegate_actions.mjs
import { chromium, firefox, webkit } from 'playwright';
import assert from 'node:assert/strict';
// Runs in the page: dispatch table + one listener, no querySelector on the click path.
function installActions(container, handlers) {
const onClick = (event) => {
const el = event.target.closest('[data-action]'); // walks up from the exact node hit
if (!el || !container.contains(el)) return; // ignore matches outside the container
const fn = Object.hasOwn(handlers, el.dataset.action) && handlers[el.dataset.action];
if (typeof fn === 'function') fn(el, event);
};
container.addEventListener('click', onClick);
return () => container.removeEventListener('click', onClick);
}
const html = `<div data-action="outer-trap"><div id="list">
<button data-action="delete" data-id="1"><span class="icon"><i id="deep">x</i></span> Delete</button>
<button data-action="constructor" data-id="2">Proto name</button>
<button data-action="no-such-action" data-id="4">Unknown</button>
<p id="plain">no action</p></div></div>`;
for (const [name, type] of Object.entries({ chromium, firefox, webkit })) {
const browser = await type.launch();
const page = await browser.newPage();
const errors = [];
page.on('pageerror', (err) => errors.push(err.message)); // a throw inside the click handler must fail the run
await page.setContent(html);
const seen = [];
await page.exposeFunction('record', (s) => seen.push(s));
await page.evaluate(`(() => {
const install = ${installActions.toString()};
window.queries = 0;
for (const P of [Element.prototype, Document.prototype]) for (const m of ['querySelector','querySelectorAll']) {
const orig = P[m]; P[m] = function (...a) { window.queries++; return orig.apply(this, a); };
}
// The table inherits a 'constructor' function that records, and has an 'outer-trap' action:
// both must stay silent, so removing hasOwn or container.contains makes the run fail.
const table = Object.assign(Object.create({ constructor: () => window.record('inherited-constructor') }), {
delete: (el) => window.record('delete:' + el.dataset.id),
archive: (el) => window.record('archive:' + el.dataset.id),
'outer-trap': () => window.record('outer-trap'),
});
install(document.getElementById('list'), table);
})()`);
await page.click('#deep'); // nested child of the delete button
await page.evaluate(() => {
const b = document.createElement('button');
b.dataset.action = 'archive'; b.dataset.id = '3'; b.textContent = 'Archive';
document.getElementById('list').append(b);
});
await page.click('[data-id="3"]');
await page.click('[data-id="2"]'); // "constructor" is not an own key: ignored
await page.click('[data-id="4"]'); // unknown action name: ignored, no exception
await page.click('#plain'); // no data-action above it inside the list
await page.waitForTimeout(100);
const queries = await page.evaluate(() => window.queries);
assert.deepEqual(seen, ['delete:1', 'archive:3']);
assert.equal(queries, 0);
assert.deepEqual(errors, []);
console.log(name, JSON.stringify(seen), 'selector-queries-on-click:', queries);
await browser.close();
}
It prints:
chromium ["delete:1","archive:3"] selector-queries-on-click: 0
firefox ["delete:1","archive:3"] selector-queries-on-click: 0
webkit ["delete:1","archive:3"] selector-queries-on-click: 0
Only the two real actions fire (in order, delete:1 then archive:3), the prototype-named action, the unknown action and the plain paragraph do nothing (the wrapper's outer-trap handler is never called), and the page ran zero selector queries on the click path. The assert calls throw if any of that stops being true.
Trade-offs and pitfalls
- Cost per click.
closestwalks up from the clicked node, so its cost is bounded by how deep that node sits in the document and does not grow with the number of items in the list. Ten thousand rows cost the same as ten. Selector queries such ascontainer.querySelectorAll('[data-action]')inside the handler would scale with the whole subtree, which is the cost the question asks you to avoid. - One listener per event type. If actions also respond to
keydown(Enter on a focused item) orchange, install a second delegated listener for that type; the same table can serve both. Native<button>elements already turn Enter and Space intoclick, which is another reason to use buttons for actions instead of<div>. - Handlers that stop propagation hide the event from the container. Search for
stopPropagationfirst when one action "never fires". - Where the table lives. Keep
handlersas a plain object in the module that owns the list, so adding an action means adding one key. If an action needs arguments, read them from otherdata-*attributes (dataset.idabove) rather than closing over per-item state.
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 delegate_actions.mjs, then run:
node delegate_actions.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.
A click listener on a web component's host element reports the host, not the inner button that was clicked. Explain why, whether a listener outside the shadow root can ever see the real origin, and what that means for delegation across component boundaries.
Sample Answer
Direct answer
The host is reported because the browser retargets (rewrites) event.target for every listener that sits outside the shadow tree. Shadow DOM is a private DOM subtree that a custom element attaches to itself, and the host is the element that subtree hangs from; its purpose is to hide the component's internals, so code outside sees the host element, never the inner button. A listener inside the shadow root still sees the real button. Outside code can recover the real origin only when the shadow root (the top node of the private subtree) is open, by reading event.composedPath()[0] while the event is being dispatched; with a closed root the path starts at the host, so the origin is unreachable by design. For delegation this means a document-level event.target.closest('[data-action]') works for light DOM and slotted content but is blind to shadow-internal controls, so components should announce what happened with their own custom events marked composed (allowed to cross the shadow boundary) instead of making outsiders look inside.
The pieces
A custom element is an HTML tag you define with a JavaScript class. This one, <x-card>, attaches a private subtree to itself with attachShadow. After the component runs, the page looks like this:
x-card#openCard <- the host: a normal element in the page
#shadow-root (open) <- the shadow root: top of the private subtree
div
button[data-action=buy] <- the inner button: hidden from outside code
- Shadow tree and shadow root: the private subtree, and its top node. Selectors and
querySelectorcalls made from the page do not see inside it. - Host: the ordinary element (
x-card) that owns the shadow root. It is the only part of the component that the page's own DOM contains. - Light DOM: the regular children written between the host's tags in the page's markup, for example the
<button id="slotted">inside<x-panel>. <slot>and slotted content: a<slot>is a placeholder inside the shadow tree. Light DOM children of the host are displayed there ("slotted"), but they still belong to the page's tree, not the shadow tree.- Open and closed mode:
attachShadow({ mode: 'open' })lets outside code reach the shadow root throughhost.shadowRoot.mode: 'closed'makeshost.shadowRootreturnnull. - Retargeting: while an event travels up, the browser shows each listener a target that is in the same tree as that listener. For a listener outside the shadow tree, the inner button is replaced by the host.
- Composed: an event flag. A composed event may cross the shadow boundary on its way up; a non-composed event stops at the shadow root. Events fired by the browser for a real user action (the "user agent", or UA, is the browser) such as
clickare composed. - Event delegation: one listener on an ancestor, here
document, that works out which descendant was clicked fromevent.target.
Why the host is reported
- A click on the inner button starts an event whose path is built from the button upward: button, its parent in the shadow tree, the shadow root, the host,
body,html,document,window.clickand the other user-interface events dispatched by the browser arecomposed, which means they are allowed to leave the shadow tree (MDN: "All UA-dispatched UI events are composed"). - When dispatch invokes a listener, it sets
event.targetrelative to where the listener lives. For a listener on the host or anywhere above it, the DOM standard records the host as the target for the part of the path outside the shadow tree. The inner button is never offered to them. - A listener registered on the shadow root, or on anything inside it, is in the same tree as the button, so it gets the button.
composedPath()is only populated during dispatch. After dispatch finishes the standard empties the path, so a stored event returns an empty list (the test checks this).
Can an outside listener see the real origin
| Shadow root mode | composedPath() seen by a document listener | Real origin available outside? |
|---|---|---|
open | button, div, shadow root, host, ... | Yes: event.composedPath()[0] (and host.shadowRoot is reachable) |
closed | host, body, html, document | No: nodes inside a closed tree are left out of the path (MDN: listeners "only propagate as far as" the host) |
Two more rules from the run below. First, closest() climbs through parent elements, and the shadow root is not an element and is not treated as the child of its host in the node tree. Starting from the real button it checks the button, then the div, then runs out of ancestors, so composedPath()[0].closest('x-card') returns null for an open component even though the host is in the event's path. Event paths hop across the boundary to the host; closest() does not. Second, a plain new CustomEvent(name, { bubbles: true }) dispatched from inside the shadow tree never reaches document, because composed defaults to false (MDN). Reaching bubble-phase listeners above the host needs both bubbles: true (the event travels up through ancestors) and composed: true (it may leave the shadow tree).
What it means for delegation
Event delegation is one listener on a stable ancestor that inspects event.target to decide what was clicked. Across shadow boundaries:
- Light DOM and slotted content work normally. A button placed inside
<x-panel>as a child is still in the document tree even though it is rendered through a<slot>; thedocumentlistener seesbutton#slottedas the target andclosest('[data-action]')finds it (checked below). - Shadow-internal controls do not. The
documentlistener sees the host, soclosest('[data-action]')returns nothing even though the inner button has the attribute. - Prefer a component contract over peeking. Recommendation: the component handles clicks on its own internals with a listener on its shadow root and re-announces the meaning as
new CustomEvent('card-action', { bubbles: true, composed: true, detail: { action } }). Outer delegation then keys on event names anddetail, works for open and closed roots, and survives refactoring of the inner markup. composedPath()[0]delegation is the fallback for open roots you do not control. It couples the outside code to the component's internal structure, so it breaks when the markup changes or the root is closed.- Choose
closedonly for real encapsulation needs. It also makeshost.shadowRootreturnnull, so tests and other code cannot reach inside.
The proof
The test uses Playwright (a library that drives real browsers from Node). In the component, class XCard extends HTMLElement defines the new tag, #root is a private class field holding the shadow root, connectedCallback runs when the tag enters the page, and customElements.define('x-card', XCard) registers the tag name. The component keeps its root in a private field, so the same test drives open and closed cases through a pressInner() hook. It reports, for each browser, what the host listener, the document listener and a listener inside the root saw, plus the path and delegation results. It runs in Chromium, Firefox and WebKit (Playwright's WebKit build, not Safari on a device).
import { chromium, firefox, webkit } from 'playwright';
import assert from 'node:assert/strict';
const html = `<!doctype html><body>
<x-card id="openCard"></x-card>
<x-card id="closedCard" mode="closed"></x-card>
<x-panel id="panel"><button id="slotted" data-action="save">Save</button></x-panel>
<script>
class XCard extends HTMLElement {
#root;
connectedCallback() {
this.#root = this.attachShadow({ mode: this.getAttribute('mode') || 'open' });
this.#root.innerHTML = '<div><button data-action="buy">Buy</button></div>';
const btn = this.#root.querySelector('button');
// A listener inside the shadow tree sees the real target.
this.#root.addEventListener('click', (e) => { this.targetSeenInsideRoot = e.target.tagName.toLowerCase(); });
btn.addEventListener('click', () => {
// composed: true lets the event leave the shadow tree; the default is false.
btn.dispatchEvent(new CustomEvent('card-action', { bubbles: true, composed: true, detail: { action: 'buy' } }));
btn.dispatchEvent(new CustomEvent('card-plain', { bubbles: true }));
});
}
pressInner() { this.#root.querySelector('button').click(); } // test hook that works for closed roots too
}
customElements.define('x-card', XCard);
class XPanel extends HTMLElement {
connectedCallback() { this.attachShadow({ mode: 'open' }).innerHTML = '<div class="frame"><slot></slot></div>'; }
}
customElements.define('x-panel', XPanel);
</script></body>`;
function probe(id) {
const d = (n) => (n.id ? n.tagName.toLowerCase() + '#' + n.id : (n.tagName || n.nodeName).toLowerCase());
const host = document.getElementById(id);
const o = { sawPlainEvent: false, sawCardAction: null };
let stored;
const onHost = (e) => { o.targetSeenByHostListener = d(e.target); };
const onDoc = (e) => {
stored = e;
o.targetSeenByDocumentListener = d(e.target);
o.composedPath = e.composedPath().slice(0, 4).map(d).join(' > ');
o.closestFindsAction = e.target.closest('[data-action]') !== null; // naive delegation
const origin = e.composedPath()[0];
o.delegationViaPath = origin.matches?.('[data-action]') === true; // path-aware delegation
if (id === 'openCard') o.closestFromOriginReachesHost = origin.closest('x-card') != null; // closest() stops at the shadow root
};
const onAction = (e) => { o.sawCardAction = e.detail.action + ' from ' + d(e.target); };
const onPlain = () => { o.sawPlainEvent = true; };
host.addEventListener('click', onHost);
document.addEventListener('click', onDoc);
document.addEventListener('card-action', onAction);
document.addEventListener('card-plain', onPlain);
host.pressInner();
o.targetSeenInsideRoot = host.targetSeenInsideRoot;
o.composedPathAfterDispatch = stored.composedPath().length;
host.removeEventListener('click', onHost); document.removeEventListener('click', onDoc);
document.removeEventListener('card-action', onAction); document.removeEventListener('card-plain', onPlain);
return o;
}
function probeSlotted() {
const d = (n) => (n.id ? n.tagName.toLowerCase() + '#' + n.id : (n.tagName || n.nodeName).toLowerCase());
const o = {};
const onDoc = (e) => {
o.targetSeenByDocumentListener = d(e.target);
o.composedPath = e.composedPath().slice(0, 4).map(d).join(' > ');
o.closestFindsAction = e.target.closest('[data-action]') !== null;
};
document.addEventListener('click', onDoc);
document.getElementById('slotted').click();
document.removeEventListener('click', onDoc);
return o;
}
function probeComposedOnly() {
const host = document.getElementById('openCard');
const seen = [];
const watch = (name, target, capture) => target.addEventListener('card-composed-only', (e) => seen.push(name + ':phase' + e.eventPhase), capture);
watch('host-capture', host, true); watch('host-bubble', host, false);
watch('document-capture', document, true); watch('document-bubble', document, false);
const btn = host.shadowRoot.querySelector('button');
btn.dispatchEvent(new CustomEvent('card-composed-only', { composed: true })); // composed, but no bubbles
return seen.join(' ');
}
for (const bt of [chromium, firefox, webkit]) {
const browser = await bt.launch();
const page = await browser.newPage();
await page.setContent(html);
const open = await page.evaluate(probe, 'openCard');
const closed = await page.evaluate(probe, 'closedCard');
const slotted = await page.evaluate(probeSlotted);
const composedOnly = await page.evaluate(probeComposedOnly);
console.log(`${bt.name()} composed without bubbles: ${composedOnly}`);
const line = (label, o) => console.log(`${bt.name()} ${label}: host listener target=${o.targetSeenByHostListener ?? '-'}, document listener target=${o.targetSeenByDocumentListener}, listener inside root target=${o.targetSeenInsideRoot ?? '-'}, composedPath=[${o.composedPath}], closest() finds data-action=${o.closestFindsAction}, composedPath()[0] finds it=${o.delegationViaPath ?? '-'}, closest('x-card') from the real origin=${o.closestFromOriginReachesHost ?? '-'}, composed custom event=${o.sawCardAction ?? '-'}, non-composed custom event reached document=${o.sawPlainEvent ?? '-'}`);
line('open ', open);
line('closed', closed);
line('slotted', slotted);
assert.equal(open.targetSeenByHostListener, 'x-card#openCard');
assert.equal(open.targetSeenByDocumentListener, 'x-card#openCard');
assert.equal(open.closestFindsAction, false);
assert.equal(closed.closestFindsAction, false);
assert.equal(open.delegationViaPath, true);
assert.equal(open.closestFromOriginReachesHost, false);
assert.equal(closed.delegationViaPath, false);
assert.equal(closed.composedPath.startsWith('x-card#closedCard'), true);
assert.equal(open.composedPath.startsWith('button'), true);
assert.equal(open.sawPlainEvent, false);
assert.equal(open.sawCardAction, 'buy from x-card#openCard');
assert.equal(closed.sawCardAction, 'buy from x-card#closedCard');
assert.equal(open.composedPathAfterDispatch, 0);
assert.equal(open.targetSeenInsideRoot, 'button');
assert.equal(closed.targetSeenInsideRoot, 'button');
assert.equal(composedOnly, 'document-capture:phase1 host-capture:phase2 host-bubble:phase2');
assert.equal(slotted.targetSeenByDocumentListener, 'button#slotted');
assert.equal(slotted.closestFindsAction, true);
assert.equal(slotted.composedPath, 'button#slotted > slot > div > #document-fragment');
await browser.close();
}
console.log('all shadow DOM checks passed');
Each output line is one browser and one case (open, closed, or slotted), with fields separated by commas. Reading the fields for the open line:
| Field | Value in the open case | What it shows |
|---|---|---|
host listener target | x-card#openCard | A listener on the host sees the host, not the button |
document listener target | x-card#openCard | Retargeting also applies at document |
listener inside root target | button | A listener within the shadow tree gets the real target |
composedPath | button > div > #document-fragment > x-card#openCard | The first four entries of the path; #document-fragment is the shadow root |
closest() finds data-action | false | Naive delegation on event.target fails |
composedPath()[0] finds it | true | Path-aware delegation works when the root is open |
closest('x-card') from the real origin | false | closest() cannot climb out of the shadow tree |
composed custom event | buy from x-card#openCard | The component's own composed event arrives with its detail |
non-composed custom event reached document | false | Without composed: true it never leaves |
Each browser also prints a composed without bubbles line for an event created with composed: true and no bubbles: it lists which host and document listeners ran and in which phase (phase1 is capture, phase2 is at-target). The closed line differs in three fields: composedPath starts at the host (the inner nodes are left out), composedPath()[0] finds it is false, and the closest('x-card') field is - because there is no real origin to start from. A - anywhere means that probe does not apply to that case. The slotted line shows the light DOM case: the document listener's target is button#slotted itself and closest() finds data-action.
Output:
chromium composed without bubbles: document-capture:phase1 host-capture:phase2 host-bubble:phase2
chromium open : host listener target=x-card#openCard, document listener target=x-card#openCard, listener inside root target=button, composedPath=[button > div > #document-fragment > x-card#openCard], closest() finds data-action=false, composedPath()[0] finds it=true, closest('x-card') from the real origin=false, composed custom event=buy from x-card#openCard, non-composed custom event reached document=false
chromium closed: host listener target=x-card#closedCard, document listener target=x-card#closedCard, listener inside root target=button, composedPath=[x-card#closedCard > body > html > #document], closest() finds data-action=false, composedPath()[0] finds it=false, closest('x-card') from the real origin=-, composed custom event=buy from x-card#closedCard, non-composed custom event reached document=false
chromium slotted: host listener target=-, document listener target=button#slotted, listener inside root target=-, composedPath=[button#slotted > slot > div > #document-fragment], closest() finds data-action=true, composedPath()[0] finds it=-, closest('x-card') from the real origin=-, composed custom event=-, non-composed custom event reached document=-
firefox composed without bubbles: document-capture:phase1 host-capture:phase2 host-bubble:phase2
firefox open : host listener target=x-card#openCard, document listener target=x-card#openCard, listener inside root target=button, composedPath=[button > div > #document-fragment > x-card#openCard], closest() finds data-action=false, composedPath()[0] finds it=true, closest('x-card') from the real origin=false, composed custom event=buy from x-card#openCard, non-composed custom event reached document=false
firefox closed: host listener target=x-card#closedCard, document listener target=x-card#closedCard, listener inside root target=button, composedPath=[x-card#closedCard > body > html > #document], closest() finds data-action=false, composedPath()[0] finds it=false, closest('x-card') from the real origin=-, composed custom event=buy from x-card#closedCard, non-composed custom event reached document=false
firefox slotted: host listener target=-, document listener target=button#slotted, listener inside root target=-, composedPath=[button#slotted > slot > div > #document-fragment], closest() finds data-action=true, composedPath()[0] finds it=-, closest('x-card') from the real origin=-, composed custom event=-, non-composed custom event reached document=-
webkit composed without bubbles: document-capture:phase1 host-capture:phase2 host-bubble:phase2
webkit open : host listener target=x-card#openCard, document listener target=x-card#openCard, listener inside root target=button, composedPath=[button > div > #document-fragment > x-card#openCard], closest() finds data-action=false, composedPath()[0] finds it=true, closest('x-card') from the real origin=false, composed custom event=buy from x-card#openCard, non-composed custom event reached document=false
webkit closed: host listener target=x-card#closedCard, document listener target=x-card#closedCard, listener inside root target=button, composedPath=[x-card#closedCard > body > html > #document], closest() finds data-action=false, composedPath()[0] finds it=false, closest('x-card') from the real origin=-, composed custom event=buy from x-card#closedCard, non-composed custom event reached document=false
webkit slotted: host listener target=-, document listener target=button#slotted, listener inside root target=-, composedPath=[button#slotted > slot > div > #document-fragment], closest() finds data-action=true, composedPath()[0] finds it=-, closest('x-card') from the real origin=-, composed custom event=-, non-composed custom event reached document=-
all shadow DOM checks passed
Pitfalls
- Read
composedPath()synchronously inside the listener. Once dispatch has finished the path is empty (the test prints this), so a handler that stores the event and inspects it later, for example inside asetTimeout, finds nothing. - Calling
stopPropagation()inside the shadow root stops the event before it reaches the host, so outer analytics listeners never see it. composed: truewithoutbubbles: trueis not enough for bubble-phase listeners: per MDN, propagation across the boundary also needsbubbles. Such an event is handled at the host as if it were at its target, and capture-phase listeners on the host and on ancestors such asdocumentstill run, but bubble-phase listeners above the host never do (thecomposed without bubblesline in the output, asserted in Chromium, Firefox and WebKit:document-capture:phase1 host-capture:phase2 host-bubble:phase2, with nodocument-bubble).- Every
composedcustom event becomes public API of the component, so name and shape it as carefully as a method.
Running the code
mkdir shadow && cd shadow # save test-shadow.mjs here
echo '{"type":"module"}' > package.json
npm i playwright@1.48.2 && npx playwright install chromium firefox webkit
node test-shadow.mjs
Run in the mcr.microsoft.com/playwright:v1.48.2-jammy container (Node 20), where the browsers are already installed.
You add a passive touch or wheel listener and then call preventDefault inside it. What happens, why does the browser behave that way, and how do you safely detect support for the options object?
Sample Answer
Direct answer
Nothing is cancelled. A listener registered with { passive: true } is a promise that it will never call preventDefault(). If it does anyway, the browser ignores the call: the event's defaultPrevented stays false, the page scrolls or zooms as usual, and the console may show a warning. Browsers insist on this because scrolling is handled off the main thread (the main thread is the single thread that runs your JavaScript and page layout; scrolling can proceed on a separate thread as long as it never has to wait for your code): if a touchstart, touchmove or wheel listener could cancel the scroll, the browser would have to wait for your JavaScript to finish on every touch before it could move the page, which makes scrolling feel laggy. A passive promise lets it start scrolling immediately.
To cancel scrolling you must register the listener as { passive: false } (and the event must be cancelable: its cancelable property is true, meaning preventDefault() is allowed to stop it). To detect whether the browser understands an options object at all, pass an object whose passive property is a getter (a property defined as a function that runs each time the property is read): browsers that support options read it, older ones treat the third argument as the boolean capture flag (true means listen in the capture phase, the downward trip of an event from window to its target; false means the bubble phase, the upward trip back) and never touch it.
Mechanism in order
- A wheel or touch gesture begins. The browser must decide whether it can scroll now or must first run listeners that might cancel it.
- For each listener on the path, the browser knows its
passiveflag. A passive listener cannot cancel, so it does not block scrolling. - Defaults matter: MDN states that
passivedefaults tofalse, "except that it defaults totrueforwheel,mousewheel,touchstart, andtouchmoveevents onWindow,Document,Document.documentElement, andDocument.body". So a baredocument.addEventListener('wheel', fn)is passive even though you did not write it, which is the usual way people hit this. A listener on an ordinary element with the same code is not passive by default. - Inside a passive listener
preventDefault()does nothing. Chromium and Firefox log a warning; WebKit logged nothing in the run below.
Verified behaviour
The page registers two wheel listeners on document that both call preventDefault(): one with no options and one with { passive: false }. A real mouse-wheel gesture is delivered by the test driver, and the script prints what each listener saw. It also runs the feature detection. It exits non-zero unless the default listener's event stayed uncancelled, the passive: false one was cancelled, and detection reported support.
// passive-listener.mjs
import { chromium, firefox, webkit } from 'playwright';
const html = `<style>body{margin:0} #tall{height:3000px}</style><div id="tall">tall</div>
<script>
// Feature detection: the browser reads .passive only if it understands the options object.
let supportsPassive = false;
try {
const opts = { get passive() { supportsPassive = true; return false; } };
window.addEventListener('probe', null, opts);
window.removeEventListener('probe', null, opts);
} catch (e) {}
window.results = { supportsPassive, seen: [] };
const record = (label) => (e) => {
e.preventDefault();
window.results.seen.push({ label, cancelable: e.cancelable, defaultPrevented: e.defaultPrevented });
};
// 1. Listener on the document with NO options: wheel defaults to passive here.
document.addEventListener('wheel', record('document, default'));
// 2. Same listener, passive:false stated explicitly.
document.addEventListener('wheel', record('document, passive:false'), { passive: false });
</script>`;
for (const [name, bt] of Object.entries({ chromium, firefox, webkit })) {
const b = await bt.launch(); const p = await b.newPage();
const warnings = [];
p.on('console', m => { if (/passive/i.test(m.text())) warnings.push(m.text()); });
await p.setContent(html);
await p.mouse.move(50, 50);
await p.mouse.wheel(0, 200);
await p.waitForFunction(() => window.results.seen.length >= 2);
const r = await p.evaluate(() => window.results);
const byLabel = Object.fromEntries(r.seen.map(s => [s.label, s.defaultPrevented]));
console.log(name, JSON.stringify({ supportsPassive: r.supportsPassive, defaultPrevented: byLabel, warning: warnings[0] ?? null }));
if (!r.supportsPassive || byLabel['document, default'] !== false || byLabel['document, passive:false'] !== true) { console.log('FAIL'); process.exitCode = 1; }
await b.close();
}
Run in the Playwright 1.48.2 image (Chromium, Firefox, WebKit; WebKit here is Playwright's build, not iOS Safari), it prints:
chromium {"supportsPassive":true,"defaultPrevented":{"document, default":false,"document, passive:false":true},"warning":"Unable to preventDefault inside passive event listener due to target being treated as passive. See https://www.chromestatus.com/feature/6662647093133312"}
firefox {"supportsPassive":true,"defaultPrevented":{"document, default":false,"document, passive:false":true},"warning":"[JavaScript Warning: \"Ignoring ‘preventDefault()’ call on event of type ‘wheel’ from a listener registered as ‘passive’.\" {file: \"about:blank line 7 > injectedScript\" line: 14}]"}
webkit {"supportsPassive":true,"defaultPrevented":{"document, default":false,"document, passive:false":true},"warning":null}
The default listener's preventDefault() had no effect in all three engines (false), while the explicit passive: false listener cancelled the event (true). The warning wording differs by engine and WebKit printed none, so do not rely on the console to find these bugs.
Does the page actually scroll?
The script above proves the cancellation flag but both listeners sit on the same page, so the passive: false one cancels the scroll and the page never gets to move. This second script uses one page per case, each with a single wheel listener that calls preventDefault(), and measures window.scrollY. It also checks the claim that the same code on an ordinary element is not passive by default:
// scroll-check.mjs
import { chromium, firefox, webkit } from 'playwright';
// One page per case; each registers a single wheel listener that calls preventDefault().
const cases = {
'document, default': 'document.addEventListener("wheel", (e) => { e.preventDefault(); window.prevented = e.defaultPrevented; });',
'document, passive:false': 'document.addEventListener("wheel", (e) => { e.preventDefault(); window.prevented = e.defaultPrevented; }, { passive: false });',
'element, default': 'document.getElementById("tall").addEventListener("wheel", (e) => { e.preventDefault(); window.prevented = e.defaultPrevented; });',
};
// Expected: does the page scroll, and was the event cancelled?
const expected = {
'document, default': { scrolled: true, prevented: false },
'document, passive:false': { scrolled: false, prevented: true },
'element, default': { scrolled: false, prevented: true },
};
for (const [name, bt] of Object.entries({ chromium, firefox, webkit })) {
const b = await bt.launch();
const out = {};
for (const [label, js] of Object.entries(cases)) {
const p = await b.newPage();
await p.setContent(`<style>body{margin:0} #tall{height:3000px}</style><div id="tall">tall</div><script>${js}</script>`);
await p.mouse.move(50, 50);
await p.mouse.wheel(0, 200);
await p.waitForFunction(() => window.prevented !== undefined);
await p.waitForTimeout(300); // give a scroll that is going to happen time to happen
out[label] = await p.evaluate(() => ({ scrolled: window.scrollY > 0, prevented: window.prevented }));
await p.close();
}
console.log(name, JSON.stringify(out));
if (JSON.stringify(out) !== JSON.stringify(expected)) { console.log('FAIL'); process.exitCode = 1; }
await b.close();
}
Run in the Playwright 1.48.2 image (Chromium, Firefox, WebKit), it prints:
chromium {"document, default":{"scrolled":true,"prevented":false},"document, passive:false":{"scrolled":false,"prevented":true},"element, default":{"scrolled":false,"prevented":true}}
firefox {"document, default":{"scrolled":true,"prevented":false},"document, passive:false":{"scrolled":false,"prevented":true},"element, default":{"scrolled":false,"prevented":true}}
webkit {"document, default":{"scrolled":true,"prevented":false},"document, passive:false":{"scrolled":false,"prevented":true},"element, default":{"scrolled":false,"prevented":true}}
The document listener with no options is passive, so the page scrolled and nothing was cancelled. The same listener with { passive: false } cancelled the scroll, and so did the option-less listener on an ordinary element.
Feature detection, and whether you still need it
The detection code above works because the engine reads opts.passive only if it knows the options-object form. Engines that predate options-object support interpret the third argument as a boolean capture, so an object is simply truthy and passive is never read. In MDN's browser compatibility data the options object arrives in Chrome 49, Firefox 49 and Safari 10 (all 2016) and in Edge 16, and never in Internet Explorer; the "available across browsers since July 2015" Baseline line on the addEventListener page covers the method itself, not the options object. So for an audience of current browsers you can pass { passive: false } directly. Keep the detector only if you ship to Internet Explorer or to browsers older than those versions, and then pass supportsPassive ? { passive: false } : false (the false fallback means "bubble phase", which is what a bare call also means).
The order of events in the detector
The getter is not called by your code. The sequence is: the script creates the options object (nothing runs yet); it calls addEventListener('probe', null, opts); a browser that understands options reads opts.passive while processing that call, which runs the getter and sets the flag; the call returns. A browser that does not understand options never reads the property, so the flag stays false. A null listener is accepted and registers nothing, so the probe has no side effects, and the following removeEventListener call is only a safety net. The same sequence traced with a log:
import { chromium, firefox, webkit } from 'playwright';
for (const [name, bt] of Object.entries({ chromium, firefox, webkit })) {
const b = await bt.launch(); const p = await b.newPage();
await p.setContent('<p>probe</p>');
const steps = await p.evaluate(() => {
const steps = [];
let supportsPassive = false;
const opts = { get passive() { steps.push('browser reads opts.passive'); supportsPassive = true; return false; } };
steps.push('calling addEventListener');
window.addEventListener('probe', null, opts); // a null listener is allowed: nothing is registered
steps.push('addEventListener returned');
window.removeEventListener('probe', null, opts);
steps.push('supportsPassive = ' + supportsPassive);
return steps;
});
console.log(name, JSON.stringify(steps));
await b.close();
}
Run in the Playwright 1.48.2 image (Chromium, Firefox, WebKit), every engine prints the same steps (shown once):
["calling addEventListener","browser reads opts.passive","addEventListener returned","supportsPassive = true"]
The getter ran between "calling addEventListener" and "addEventListener returned", which is the point where the engine read the option.
What to do instead of cancelling scroll
- If the goal is "this element must not scroll the page", use CSS:
overscroll-behavior: containon a scrolling box stops scroll chaining (the page behind starting to scroll once the inner box reaches its end);touch-action: noneorpan-yon the element declares which touch gestures the browser handles for it. No listener, no blocking. - If you truly need to cancel (a custom drag surface, a canvas pan), register the listener on that element, not on
window, as{ passive: false }, and cancel only when your code owns the gesture. A non-passive wheel or touch listener on the document makes every scroll on the page wait for your handler. - If you do not cancel, say so: add
{ passive: true }on listeners such as scroll-position trackers so the browser never waits for them.
Pitfalls
preventDefault()also does nothing on events that are not cancelable (event.cancelable === false), for example a scroll event; checkcancelablebefore assuming a bug.- A passive listener cannot be made non-passive later: remove it (
removeEventListenerwith the same capture flag) and add a new one. - A library that attaches its own
touchmoveorwheellisteners todocumentorbodygets the passive default too. If its drag handling "does nothing", look for the warning, then pass{ passive: false }where it registers.
Running the code
echo '{"type":"module"}' > package.json
docker run --rm -v "$PWD":/w -w /w mcr.microsoft.com/playwright:v1.48.2-jammy \
sh -c 'npm i --no-audit --no-fund playwright@1.48.2 && node passive-listener.mjs'
# the detector trace: save it as detector-trace.mjs and run it the same way
# the scroll check: save it as scroll-check.mjs and run it the same way
Design a lazy-loading image system for a long gallery that also loads more items as the user nears the bottom. Cover how images are observed, what happens once one loads, what you do for browsers without the underlying API, and how you avoid duplicate or runaway loads.
Sample Answer
Direct answer
Use two IntersectionObservers (a browser API that reports when an element enters or leaves the viewport, or a margin around it). One watches every image placeholder with a generous rootMargin (a margin that grows the watched area, so images start loading a little before they are visible). The other watches a single empty "sentinel" element placed after the last image and asks the server for the next page when the sentinel gets near the viewport. The server hands back a nextCursor, an opaque bookmark (the client never inspects it) that the client passes back to ask for the page after this one; null means there are no more pages. An image is unobserved the moment its src is set, a state flag makes sure only one page request is in flight, and an end of data flag stops requests for good. Browsers without the API get native loading="lazy" images plus a scroll check that runs at most once per frame.
How images are observed
- Each item is rendered as an
<img>withwidthandheightattributes and the real URL indata-src, not insrc. The browser reserves the box from the width and height, so when the file arrives nothing below it jumps (that jump is layout shift, measured as CLS, cumulative layout shift). - All placeholders are created inside a
DocumentFragment(a detached container) and appended once, so a page of 20 images causes one DOM insertion instead of 20. - The image observer is created with
rootMargin: '300px 0px'. Per MDN, a positive margin enlarges the root's box before intersections are computed, so a target counts as intersecting before it is visible, which is how you start loading early. Onlypxand%values are allowed. - The callback receives entries. Per MDN the callback also runs once right after
observe()for each new target, even when it is not visible, so the code must checkentry.isIntersectingand ignore the rest.
What happens once an image loads
Inside the callback, for each intersecting entry: call observer.unobserve(img) first, then assign img.src = img.dataset.src. Unobserving means the image is never requested twice, the observer's list of watched targets shrinks as the user scrolls, and scrolling back up does not trigger work. An error listener adds a broken class (for a placeholder style) and does not retry, because an automatic retry on a dead URL is a loop.
Browsers without IntersectionObserver
MDN lists the API as widely available since March 2019, so this path matters mostly for old embedded browsers and for tests. The code feature-detects (checks that the API exists before using it, instead of guessing from the browser's name) with 'IntersectionObserver' in window and degrades in two steps:
- Images get
loading="lazy"and their realsrcstraight away. The browser then defers them using its own distance threshold. Each engine picks its own distance, which is why the sample output below shows a different number of early requests per engine in this mode. - The sentinel is replaced by a
scrolllistener (markedpassive, which promises the browser it will not callpreventDefault(), so scrolling is never blocked) that schedules onerequestAnimationFramecheck per frame and comparessentinel.getBoundingClientRect().top - innerHeightwith 600 px.
Avoiding duplicate and runaway loads
| Hazard | Guard in the code |
|---|---|
| The sentinel fires again while a request is pending | loading flag, checked first in loadMore() |
| Requests after the last page | done becomes true when the server returns no nextCursor |
| A failing endpoint retried forever | failed flag; only retry() (a button the user presses) clears it |
| Work after the view is gone | destroyed flag, and destroy() calls disconnect() on both observers and removes the sentinel |
| A tall screen that stays near the sentinel after an append, so no new event arrives | After each successful page, unobserve then observe the sentinel to get a fresh initial report |
| The same image requested twice | unobserve right before setting src |
The re-observe row is the subtle one. An IntersectionObserver reports changes, not states. If page 1 is shorter than the viewport, the sentinel stays "intersecting" and nothing fires again, so the gallery would stall with a half-empty screen. Re-observing forces the initial report again, and the loading flag keeps that safe.
The module
// gallery.js: lazy images plus infinite loading with an IntersectionObserver sentinel.
export function createGallery(container, fetchPage, { imageMargin = '300px 0px', pageMargin = '600px 0px' } = {}) {
const hasIO = 'IntersectionObserver' in window;
const sentinel = document.createElement('div');
sentinel.className = 'sentinel';
container.after(sentinel);
let cursor = null; // opaque token from the server for the next page
let loading = false; // true while a page request is in flight
let done = false; // true once the server says there is no next page
let failed = false; // true after an error; only retry() clears it
let destroyed = false;
const imageIO = hasIO && new IntersectionObserver((entries) => {
for (const entry of entries) {
if (!entry.isIntersecting) continue;
const img = entry.target;
imageIO.unobserve(img); // each image is loaded at most once
img.src = img.dataset.src;
}
}, { rootMargin: imageMargin });
const pageIO = hasIO && new IntersectionObserver((entries) => {
if (entries.some((e) => e.isIntersecting)) loadMore();
}, { rootMargin: pageMargin });
function render(items) {
const frag = document.createDocumentFragment();
for (const item of items) {
const img = new Image();
img.alt = item.alt;
img.width = item.w; // reserved size: no layout shift when the file arrives
img.height = item.h;
img.dataset.src = item.src;
img.addEventListener('error', () => img.classList.add('broken'), { once: true });
if (hasIO) imageIO.observe(img);
else { img.loading = 'lazy'; img.src = item.src; } // fallback: native lazy loading
frag.append(img);
}
container.append(frag);
}
async function loadMore() {
if (loading || done || failed || destroyed) return; // the four guards
loading = true;
try {
const page = await fetchPage(cursor);
if (destroyed) return;
render(page.items);
cursor = page.nextCursor;
done = cursor == null;
} catch {
failed = true; // no automatic retry loop
} finally {
loading = false;
}
// An observer only reports changes. If the sentinel is still near the viewport after
// appending, nothing would fire, so ask for a fresh initial report.
if (hasIO && !done && !failed && !destroyed) { pageIO.unobserve(sentinel); pageIO.observe(sentinel); }
if (!hasIO) checkScroll();
}
let ticking = false;
function checkScroll() { // fallback sentinel check, at most once per frame
if (ticking || destroyed) return;
ticking = true;
requestAnimationFrame(() => {
ticking = false;
if (sentinel.getBoundingClientRect().top - innerHeight < 600) loadMore();
});
}
if (hasIO) pageIO.observe(sentinel);
else { addEventListener('scroll', checkScroll, { passive: true }); checkScroll(); }
return {
retry() { failed = false; loadMore(); },
destroy() {
destroyed = true;
if (hasIO) { imageIO.disconnect(); pageIO.disconnect(); }
else removeEventListener('scroll', checkScroll);
sentinel.remove();
},
};
}
The test
The test serves the module from a fake origin, intercepts every image request with Playwright (a browser automation library) and counts them, and runs in real Chromium, Firefox and WebKit. It fails if images are not lazy, if two page requests overlap, if a request happens after the last page, if a failing request is retried, if a tall viewport stalls, or if destroy() leaves a late response rendered or an observer connected. Mapping assertion to hazard:
early < PER_PAGE: images are lazy (only the ones near the first screen are requested).s.calls === PAGES: exactly one request per page and none after the last page (thedoneflag).s.maxInflight === 1: two page requests never overlap (theloadingflag).imgCount() === PAGES * PER_PAGE: every page was rendered once.srcs === imgReqs.sizeands.unobserve >= srcs: each loaded image was requested once and then unobserved.- In the no-IntersectionObserver run, every image has
loadingset tolazy: the fallback uses native lazy loading. - In
failureAndTallViewport:calls === PAGESwith a 9000 px viewport and no scrolling (no stall, via the re-observe), and the sentinel gone afterdestroy(). Then, on an 800 px viewport, page 2 is made to fail, the page is scrolled away from the sentinel and back, andcalls === 2shows that coming back into view does not retry (thefailedguard; deletingfailedfrom the guard line inloadMore()makes this assertion fail with 3 calls). Finally the image count reaching 40 afterretry()shows recovery. - In
destroyMidRequest:destroy()is called while the first page request is still in flight, and 400 ms later the page hasimgs: 0(the late response was dropped by thedestroyedflag, not rendered),disconnects: 2(both observers were disconnected) andcalls: 1. Deleting either theif (destroyed) return;line after theawaitor the twodisconnect()calls makes this assertion fail.
The test code also deletes window.IntersectionObserver in an init script (code that runs before the page's own scripts) to simulate an old browser, and replaces IntersectionObserver.prototype.unobserve and IntersectionObserver.prototype.disconnect with counting wrappers.
// test-gallery.mjs
import { chromium, firefox, webkit } from 'playwright';
import { readFileSync } from 'node:fs';
import assert from 'node:assert/strict';
const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64');
const galleryJs = readFileSync(new URL('./gallery.js', import.meta.url), 'utf8');
const PAGES = 3, PER_PAGE = 20;
const html = `<!doctype html><body style="margin:0"><div id="g"></div>
<style>#g img{display:block;width:100%;height:200px}</style>
<script type="module">
import { createGallery } from '/gallery.js';
window.inflight = 0; window.maxInflight = 0; window.calls = 0;
window.mode = 'ok';
const fetchPage = async (cursor) => {
window.calls++; window.inflight++; window.maxInflight = Math.max(window.maxInflight, window.inflight);
await new Promise((r) => setTimeout(r, 120));
window.inflight--;
if (window.mode === 'fail') throw new Error('network');
const n = cursor ?? 0;
const items = Array.from({ length: ${PER_PAGE} }, (_, i) => ({ src: '/img/' + (n * ${PER_PAGE} + i) + '.png', alt: 'photo', w: 400, h: 200 }));
return { items, nextCursor: n + 1 < ${PAGES} ? n + 1 : null };
};
window.unobserveCalls = 0; window.disconnectCalls = 0;
if ('IntersectionObserver' in window) {
const origUnobserve = IntersectionObserver.prototype.unobserve;
IntersectionObserver.prototype.unobserve = function (...a) { window.unobserveCalls++; return origUnobserve.apply(this, a); };
const origDisconnect = IntersectionObserver.prototype.disconnect;
IntersectionObserver.prototype.disconnect = function (...a) { window.disconnectCalls++; return origDisconnect.apply(this, a); };
}
window.gallery = createGallery(document.getElementById('g'), fetchPage);
</script></body>`;
async function run(browserType, { noIO = false } = {}) {
const browser = await browserType.launch();
const page = await browser.newPage({ viewport: { width: 400, height: 800 } });
const imgReqs = new Set();
await page.route('http://app.test/**', (route) => {
const u = new URL(route.request().url());
if (u.pathname === '/') return route.fulfill({ contentType: 'text/html', body: html });
if (u.pathname === '/gallery.js') return route.fulfill({ contentType: 'text/javascript', body: galleryJs });
imgReqs.add(u.pathname);
return route.fulfill({ contentType: 'image/png', body: PNG });
});
if (noIO) await page.addInitScript(() => { delete window.IntersectionObserver; });
await page.goto('http://app.test/');
await page.waitForFunction(() => window.calls >= 1 && window.inflight === 0);
const imgCount = () => page.evaluate(() => document.querySelectorAll('#g img').length);
const settle = async (n) => { await page.waitForFunction((n) => document.querySelectorAll('#g img').length >= n && window.inflight === 0, n); };
await settle(PER_PAGE);
await page.waitForTimeout(300);
const label = `${browserType.name()}${noIO ? ' (no IntersectionObserver)' : ''}`;
// 1. Only images near the first screen are requested.
const early = imgReqs.size;
if (!noIO) assert.ok(early < PER_PAGE, `${label}: expected lazy loading, got ${early} of ${PER_PAGE} requests`);
// 2. Scroll to the end in bursts while a request may be in flight.
for (let i = 0; i < 40; i++) { await page.mouse.wheel(0, 3000); await page.waitForTimeout(25); }
await page.waitForFunction(() => window.calls >= 3 && window.inflight === 0);
await page.waitForTimeout(500);
for (let i = 0; i < 10; i++) { await page.mouse.wheel(0, 3000); await page.waitForTimeout(25); }
const s = await page.evaluate(() => ({ calls: window.calls, maxInflight: window.maxInflight, unobserve: window.unobserveCalls }));
assert.equal(await imgCount(), PAGES * PER_PAGE, `${label}: all pages rendered`);
assert.equal(s.calls, PAGES, `${label}: one request per page, none after the end`);
assert.equal(s.maxInflight, 1, `${label}: never two requests at once`);
// 3. Every image that was requested was requested once (the Set would hide repeats, so count loads).
const srcs = await page.evaluate(() => [...document.querySelectorAll('#g img')].filter((i) => i.getAttribute('src')).length);
assert.equal(srcs, imgReqs.size, `${label}: one request per loaded image`);
if (!noIO) assert.ok(s.unobserve >= srcs, `${label}: images unobserved after load`);
if (noIO) assert.ok(await page.evaluate(() => [...document.querySelectorAll('#g img')].every((i) => i.loading === 'lazy')));
console.log(label, JSON.stringify({ imagesRequestedBeforeScroll: early, pageRequests: s.calls, maxInFlight: s.maxInflight }));
await browser.close();
}
async function failureAndTallViewport(browserType) {
const browser = await browserType.launch();
const page = await browser.newPage({ viewport: { width: 400, height: 9000 } });
await page.route('http://app.test/**', (route) => {
const u = new URL(route.request().url());
if (u.pathname === '/') return route.fulfill({ contentType: 'text/html', body: html });
if (u.pathname === '/gallery.js') return route.fulfill({ contentType: 'text/javascript', body: galleryJs });
return route.fulfill({ contentType: 'image/png', body: PNG });
});
await page.goto('http://app.test/');
// A viewport tall enough to show several pages: loading must continue without any scroll event.
await page.waitForFunction((n) => document.querySelectorAll('#g img').length === n && window.inflight === 0, PAGES * PER_PAGE);
assert.equal(await page.evaluate(() => window.calls), PAGES);
// destroy() disconnects both observers and removes the sentinel
await page.evaluate(() => window.gallery.destroy());
assert.equal(await page.evaluate(() => document.querySelector('.sentinel')), null);
console.log(browserType.name(), 'tall viewport filled without scrolling:', PAGES, 'requests');
await browser.close();
const b2 = await browserType.launch();
const p2 = await b2.newPage({ viewport: { width: 400, height: 800 } });
await p2.route('http://app.test/**', (route) => {
const u = new URL(route.request().url());
if (u.pathname === '/') return route.fulfill({ contentType: 'text/html', body: html });
if (u.pathname === '/gallery.js') return route.fulfill({ contentType: 'text/javascript', body: galleryJs });
return route.fulfill({ contentType: 'image/png', body: PNG });
});
await p2.goto('http://app.test/');
await p2.waitForFunction((n) => document.querySelectorAll('#g img').length === n && window.inflight === 0, PER_PAGE);
await p2.evaluate(() => { window.mode = 'fail'; }); // page 2 will fail
const toBottom = () => p2.evaluate(() => scrollTo(0, document.body.scrollHeight));
await toBottom();
await p2.waitForFunction(() => window.calls === 2 && window.inflight === 0);
await p2.waitForTimeout(300);
// Leave the sentinel's zone and come back: this is what would fire a second request if nothing stopped it.
await p2.evaluate(() => scrollTo(0, 0));
await p2.waitForTimeout(300);
await toBottom();
await p2.waitForTimeout(500);
assert.equal(await p2.evaluate(() => window.calls), 2, 'a failed request is not retried when the sentinel comes back into view');
await p2.evaluate(() => { window.mode = 'ok'; window.gallery.retry(); });
await p2.waitForFunction(() => document.querySelectorAll('#g img').length === 40);
console.log(browserType.name(), 'failure: 2 requests (the second failed), none on re-entry; retry() recovered');
await b2.close();
}
async function destroyMidRequest(browserType) {
const browser = await browserType.launch();
const page = await browser.newPage({ viewport: { width: 400, height: 800 } });
await page.route('http://app.test/**', (route) => {
const u = new URL(route.request().url());
if (u.pathname === '/') return route.fulfill({ contentType: 'text/html', body: html });
if (u.pathname === '/gallery.js') return route.fulfill({ contentType: 'text/javascript', body: galleryJs });
return route.fulfill({ contentType: 'image/png', body: PNG });
});
await page.goto('http://app.test/');
await page.waitForFunction(() => window.inflight === 1); // the first page request is on its way
await page.evaluate(() => window.gallery.destroy()); // the view goes away before the response arrives
await page.waitForTimeout(400);
const after = await page.evaluate(() => ({ imgs: document.querySelectorAll('#g img').length, disconnects: window.disconnectCalls, calls: window.calls }));
assert.deepEqual(after, { imgs: 0, disconnects: 2, calls: 1 });
console.log(browserType.name(), 'destroy() during a request:', JSON.stringify(after));
await browser.close();
}
for (const bt of [chromium, firefox, webkit]) {
await run(bt);
await run(bt, { noIO: true });
await failureAndTallViewport(bt);
await destroyMidRequest(bt);
}
console.log('all gallery checks passed');
Sample run (the 6 in imagesRequestedBeforeScroll is derived under Worked numbers below; the number of early requests in the "no IntersectionObserver" lines depends on each engine's native lazy-loading distance; WebKit here is Playwright's build, not Safari on a device):
chromium {"imagesRequestedBeforeScroll":6,"pageRequests":3,"maxInFlight":1}
chromium (no IntersectionObserver) {"imagesRequestedBeforeScroll":19,"pageRequests":3,"maxInFlight":1}
chromium tall viewport filled without scrolling: 3 requests
chromium failure: 2 requests (the second failed), none on re-entry; retry() recovered
chromium destroy() during a request: {"imgs":0,"disconnects":2,"calls":1}
firefox {"imagesRequestedBeforeScroll":6,"pageRequests":3,"maxInFlight":1}
firefox (no IntersectionObserver) {"imagesRequestedBeforeScroll":8,"pageRequests":3,"maxInFlight":1}
firefox tall viewport filled without scrolling: 3 requests
firefox failure: 2 requests (the second failed), none on re-entry; retry() recovered
firefox destroy() during a request: {"imgs":0,"disconnects":2,"calls":1}
webkit {"imagesRequestedBeforeScroll":6,"pageRequests":3,"maxInFlight":1}
webkit (no IntersectionObserver) {"imagesRequestedBeforeScroll":9,"pageRequests":3,"maxInFlight":1}
webkit tall viewport filled without scrolling: 3 requests
webkit failure: 2 requests (the second failed), none on re-entry; retry() recovered
webkit destroy() during a request: {"imgs":0,"disconnects":2,"calls":1}
all gallery checks passed
Removing the loading || check from loadMore() makes the test fail with duplicate pages rendered (more than the expected 60 images), so the guard is what the test is measuring. With that one condition deleted, the same test run stops at the first engine's fallback run:
chromium {"imagesRequestedBeforeScroll":6,"pageRequests":3,"maxInFlight":1}
AssertionError [ERR_ASSERTION]: chromium (no IntersectionObserver): all pages rendered
actual: 80,
expected: 60,
The 80 images exceed the 60 that the three pages hold, so at least one page was rendered twice, which is what overlapping requests produce.
Worked numbers
The numbers behind the imagesRequestedBeforeScroll: 6 and "tall viewport" lines are worked out here. The test data is 3 pages of 20 images, each image box 200 px tall, so one page is 20 x 200 = 4000 px and the gallery is 12 000 px. With a 800 px viewport, the image margin of 300 px means about (800 + 300) / 200 = 5.5, so 6 images are requested at the start, which matches the imagesRequestedBeforeScroll: 6 lines. In the 9000 px viewport, the sentinel sits at 4000 px after page 1 and at 8000 px after page 2, both inside 9000 + 600 px, so all 3 pages load without any scroll, which is the "tall viewport" line.
Trade-offs and pitfalls
- Native
loading="lazy"alone is enough for images and needs no JavaScript, but it gives no hook for infinite loading and no control over distance. The observer version buys control and the sentinel. - If the gallery scrolls inside its own container instead of the page, pass that element as the observer's
root; otherwise the viewport is the root and the sentinel never intersects. rootMarginis a tuning knob: larger values hide latency and waste bandwidth for users who stop scrolling.- Thousands of appended images still cost memory and layout. Past a few hundred items, virtualization (rendering only the rows near the viewport and recycling them) is the next step; it changes the design, so decide it up front for galleries that can reach that size.
- Complexity: each image costs O(1) observer registration and is removed after loading; each page costs one request and one fragment insertion.
Running the code
mkdir gallery && cd gallery # save gallery.js and test-gallery.mjs here
echo '{"type":"module"}' > package.json
npm i playwright@1.48.2 && npx playwright install chromium firefox webkit
node test-gallery.mjs
Run in the mcr.microsoft.com/playwright:v1.48.2-jammy container (Node 20), where the browsers are already installed.
Walk through the ways to select elements in the DOM and what each returns. Which results are live and which are static, and how could that difference bite you in a loop?
Sample Answer
Direct answer
Every selection method answers "which elements match", but they differ in what they return and whether the result keeps updating. getElementById returns one element or null. querySelector returns the first match or null. getElementsByClassName, getElementsByTagName and the children property return a live HTMLCollection: it re-evaluates against the document every time you read it. querySelectorAll returns a static NodeList: a snapshot taken at the call. A snapshot is a fixed copy of the matches as they were at that instant; later changes to the page do not add to it or remove from it, whereas a live collection is a view that always reflects the page as it is now. The trap in a loop is that changing the DOM while walking a live collection changes the collection under you, so the loop skips items.
The methods and what they return
| Method | Returns | Live? | Typical use |
|---|---|---|---|
document.getElementById('x') | Element or null | n/a | Known unique id; document-level only |
el.querySelector(sel) | first matching Element or null | n/a | One element, any CSS selector |
el.querySelectorAll(sel) | NodeList | No, static | Many elements, then iterate or modify |
el.getElementsByClassName(c) | HTMLCollection | Yes | Rarely: when you want a view that tracks the page |
el.getElementsByTagName(t) | HTMLCollection | Yes | Same |
el.children | HTMLCollection of child elements | Yes | Walking direct children |
el.childNodes | NodeList of child nodes, text included | Yes (a NodeList can be live) | Walking text and comment nodes too |
A NodeList from querySelectorAll has forEach; an HTMLCollection does not, and neither has map or filter until you wrap it with Array.from(...). MDN documents querySelectorAll as returning "a static (not live) NodeList" and getElementsByClassName as a live HTMLCollection ("Be aware of this for iteration purposes"). An invalid selector string makes querySelector* throw a SyntaxError; the getElementsBy* methods take a plain name, not a selector.
Relative performance: choose by semantics rather than speed. An id lookup is a lookup by name, while a selector query has to test candidate elements against the selector, and querySelectorAll does that matching once, up front, for the whole result. For ordinary pages neither is worth micro-optimizing, and a live collection costs you correctness (the trap in the next section) before it saves you anything.
Worked example: the loop that skips items
The page has four <li class="item">. The script checks the return types, appends a fifth item, then removes the class item from every element in a loop, once over the live collection and once over a static snapshot. Two lines may look unfamiliar: .constructor.name reads the name of the class an object was built from, which is how the script prints HTMLCollection versus NodeList; and Object.assign(document.createElement('li'), { className: 'item', textContent: '5' }) creates a new <li> and copies those two properties onto it in one expression, so it has class item and text 5 before append puts it in the list.
// live_static.mjs
import { chromium, firefox, webkit } from 'playwright';
import assert from 'node:assert/strict';
const html = `<ul id="list"><li class="item">1</li><li class="item">2</li>
<li class="item">3</li><li class="item">4</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 kinds = {
byId: document.getElementById('list').constructor.name,
byClass: document.getElementsByClassName('item').constructor.name,
byTag: document.getElementsByTagName('li').constructor.name,
qs: document.querySelector('.item').constructor.name,
qsa: document.querySelectorAll('.item').constructor.name,
children: document.getElementById('list').children.constructor.name,
childNodes: document.getElementById('list').childNodes.constructor.name,
};
const list = document.getElementById('list');
const live = document.getElementsByClassName('item');
const snap = document.querySelectorAll('.item');
const before = [live.length, snap.length];
list.append(Object.assign(document.createElement('li'), { className: 'item', textContent: '5' }));
const after = [live.length, snap.length];
// The trap: removing the class while walking a live collection
for (let i = 0; i < live.length; i++) live[i].classList.remove('item');
const leftAfterLiveLoop = live.length;
// Same loop over a static snapshot
list.querySelectorAll('li').forEach((li) => li.classList.add('item'));
for (const el of document.querySelectorAll('.item')) el.classList.remove('item');
const leftAfterStaticLoop = document.getElementsByClassName('item').length;
return { kinds, before, after, leftAfterLiveLoop, leftAfterStaticLoop };
});
console.log(name, JSON.stringify(r));
assert.deepEqual(r.before, [4, 4]);
assert.deepEqual(r.after, [5, 4]);
assert.equal(r.leftAfterLiveLoop, 2); // 5 items, every other one skipped (3 removed)
assert.equal(r.leftAfterStaticLoop, 0);
await browser.close();
}
Output (Chromium; Firefox and WebKit print the same values):
chromium {"kinds":{"byId":"HTMLUListElement","byClass":"HTMLCollection","byTag":"HTMLCollection","qs":"HTMLLIElement","qsa":"NodeList","children":"HTMLCollection","childNodes":"NodeList"},"before":[4,4],"after":[5,4],"leftAfterLiveLoop":2,"leftAfterStaticLoop":0}
- After the append, the live collection reports 5 but the snapshot still holds the original 4 (
"before":[4,4],"after":[5,4]). - In the live loop, index
0loses its class and leaves the collection, so every later item shifts down one slot whileimoves up. With 5 items the loop touched positions holding items 1, 3 and 5 and left 2 and 4 behind:leftAfterLiveLoopis 2. - The loop over
querySelectorAllvisits all five:leftAfterStaticLoopis 0.
Fixes and where the gotcha bites
- Iterate a static source:
querySelectorAll, or copy first withArray.from(live)or[...live]. - Or walk a live collection backwards (
for (let i = live.length - 1; i >= 0; i--)) when you only remove: removing the item atishifts only items you have already passed. - Adding matching elements while looping a live collection grows the length your loop condition re-reads, so the loop's own end moves. Take a snapshot first.
NodeListis not always static:childNodesis live too. Do not infer "static" from the type name; read the method's documentation.- A snapshot is also the safer default in UI test and automation scripts, where the page may re-render between two reads.
Running the code
mkdir demo && cd demo
echo '{"type":"module"}' > package.json # save the listing as live_static.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 live_static.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.
Unlock Full Question Bank
Get access to all DOM Manipulation and Browser APIs interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.