关于将被动addEventListener替换为onTouchStart及被动事件监听器的疑问
preventDefault()? Great question! Your core understanding is mostly correct—passive event listeners are tightly linked to whether you intend to call event.preventDefault() in your handler, but there’s a bit more context around why this matters for browser performance and behavior.
Let’s break down your examples first
- When you set
passive: true(like your originaldocument.addEventListener('touchstart', handler, {passive: true}), which translates toonTouchStart={handler}in React-like syntax), you’re telling the browser: "This handler will never callpreventDefault()". So yourhandlerwithoutpreventDefault()is exactly the right approach here. If you did try to callevent.preventDefault()in a passive listener, most modern browsers will ignore it and throw a console warning—since you explicitly promised not to block the default behavior. - When
passive: false(the default for most events, unless the browser overrides it), you’re giving yourself permission to callevent.preventDefault()to block the browser’s default action (like stopping page scrolling on atouchstartevent). Your handler withevent.preventDefault()is perfect for this case.
Beyond just preventDefault(): The performance angle
The real reason passive listeners exist is to fix a common performance bottleneck with scroll/touch events. Before passive listeners, browsers had to wait for all event handlers to finish executing before they could start handling the default behavior (like scrolling the page). If a handler was slow, this caused noticeable jank.
By setting passive: true, you let the browser know it can immediately start processing the default behavior (e.g., scrolling) without waiting for your handler to run. The tradeoff is you lose the ability to cancel that default behavior with preventDefault().
A quick note on browser defaults
Some modern browsers (like Chrome) automatically set passive: true for touchstart and touchmove listeners on document/window level, because these events are frequently tied to scrolling. If you need to call preventDefault() for these events, you must explicitly set passive: false—otherwise, your preventDefault() call will be ignored.
Final takeaway
Your core understanding is correct: the key distinction of passive listeners is whether you plan to use preventDefault() to block default browser behavior. But it’s also important to remember that this feature was primarily built to improve scroll performance, which is why it’s most relevant for touch and scroll-related events.
内容的提问来源于stack exchange,提问作者Aleksandra

