Prototype Chain Prototype Chain - 1 year ago 266
Javascript Question

What are passive event listeners?

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 describe the concept of Passive event listeners.

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

Answer Source

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 enable developers to opt-in to better scroll performance by eliminating the need for scrolling to block on touch and wheel event listeners.


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.

addEventListener(document, "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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download