Passive Listeners Keep Scrolling Cheap
Mark wheel and touch listeners as passive so the browser scrolls immediately without waiting for preventDefault decisions in handlers.
Code
// For wheel and touch events the browser must know up front whether
// the listener might call preventDefault. passive: true promises it
// never will, so the browser starts scrolling immediately instead of
// waiting for every handler — this is what keeps scrolling cheap.
const feed = document.querySelector('#feed');
// Read-only analytics listener: passive is the whole point
feed.addEventListener('wheel', (event) => {
recordScrollDepth(event.deltaY);
}, { passive: true });
// Touch listeners benefit most, because a cancelable touchstart
// blocks scrolling while it waits for the handler
feed.addEventListener('touchstart', (event) => {
markTouchOrigin(event.timeStamp);
}, { passive: true });
// A listener that genuinely blocks scrolling stays non-passive
feed.addEventListener('touchstart', (event) => {
if (isOverDragHandle(event.target)) {
event.preventDefault();
}
}, { passive: false });
function recordScrollDepth(deltaY) {
console.log(`scroll delta ${deltaY}`);
}
function markTouchOrigin(timeStamp) {
console.log(`touch at ${timeStamp}`);
}
function isOverDragHandle(target) {
return target.dataset.handle === 'true';
}What the passive flag promises
For wheel and touchstart the browser must know up front whether a listener might call preventDefault; { passive: true } promises it never will, so scrolling starts immediately instead of waiting for the handler. The file registers three listeners on #feed: a passive wheel listener for analytics (recordScrollDepth(event.deltaY)), a passive touchstart for origin marking (markTouchOrigin(event.timeStamp)), and — deliberately — a third non-passive touchstart that checks isOverDragHandle(event.target) and only then calls event.preventDefault().
Runtime and output
Real wheel and touch events exist only in a browser, so run this against a page, not a bare interpreter. When the listeners fire, each handler logs one tagged line — scroll delta … from the wheel handler, touch at … from the touch handler — so console output maps one-to-one to the listener that produced it.
The line that stays non-passive
feed.addEventListener('touchstart', (event) => {
if (isOverDragHandle(event.target)) {
event.preventDefault();
}
}, { passive: false });
A listener that genuinely blocks scrolling (the drag-handle case) cannot be passive — the two touchstart declarations sit side by side precisely to show which one needs the flag.
Interactive Tools for This Topic
FAQ
- Does Passive Listeners Keep Scrolling Cheap run in plain Node.js?
- No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.