328

While working around to boost performance for progressive web apps, I came across a new feature Passive Event Listeners and I find it hard to understand the concept.

What are Passive Event Listeners and what is the need to have it in our projects?

1

1 Answer 1

392

Passive event listeners are an emerging web standard, new feature shipped in Chrome 51 that provide a major potential boost to scroll performance. Chrome Release Notes.

It enables developers to opt-in to better scroll performance by eliminating the need for scrolling to block on touch and wheel event listeners.

Problem: All modern browsers have a threaded scrolling feature to permit scrolling to run smoothly even when expensive JavaScript is running, but this optimization is partially defeated by the need to wait for the results of any touchstart and touchmove handlers, which may prevent the scroll entirely by calling preventDefault() on the event.

Solution: {passive: true}

By marking a touch or wheel listener as passive, the developer is promising the handler won't call preventDefault to disable scrolling. This frees the browser up to respond to scrolling immediately without waiting for JavaScript, thus ensuring a reliably smooth scrolling experience for the user.

document.addEventListener("touchstart", function(e) {
    console.log(e.defaultPrevented);  // will be false
    e.preventDefault();   // does nothing since the listener is passive
    console.log(e.defaultPrevented);  // still false
}, Modernizr.passiveeventlisteners ? {passive: true} : false);

DOM Spec , Demo Video , Explainer Doc

7
  • 4
    so we should always add this lines of code (at least for most cases), right? Jun 12, 2016 at 3:33
  • 2
    This crashes your js engine in Mozilla. You better detect the browser before attaching this event listener Sep 19, 2016 at 13:01
  • @AltianoGerung When the browser recommends it. You will see the message in the Console's Info or Warning tab.
    – snowYetis
    Oct 14, 2016 at 13:34
  • @yardpenalty.com We can use the following polyfill and avoid the browser checks. For scrolling use cases, using passive event listeners is a big plus. github.com/WICG/EventListenerOptions/blob/gh-pages/… Apr 28, 2020 at 20:30
  • 2
    So, in simple words the passive event listener is such an event handler that can not call the preventDefault function. Do I understand correctly? Jun 5, 2020 at 10:50

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.