Consider marking event handler as ‘passive’ to make the page more responsive

I am using hammer for dragging and it is getting choppy when loading other stuff, as this warning message is telling me.

Handling of ‘touchstart’ input event was delayed for X ms due to main thread being busy. Consider marking event handler as ‘passive’ to make the page more responsive.

So I tried to add ‘passive’ to the listener like so:

[php]Hammer(element[0]).on("touchstart", function(ev) {
// stuff
}, {
passive: true
});[/php]

but I’m still getting this warning.

Best Answer

For those receiving this warning for the first time, it is due to a bleeding edge feature called Passive Event Listeners that has been implemented in browsers fairly recently (summer 2016). From https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md:

Passive event listeners are a new feature in the DOM spec that enable developers to opt-in to better scroll performance by eliminating the need for scrolling to block on touch and wheel event listeners. Developers can annotate touch and wheel listeners with {passive: true} to indicate that they will never invoke preventDefault. This feature shipped in Chrome 51, Firefox 49 and landed in WebKit. For full official explanation read more here.

Details:

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.

[php]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);[/php]

You may have to wait for your .js library to implement support.

If you are handling events indirectly via a JavaScript library, you may be at the mercy of that particular library’s support for the feature. As of December 2019, it does not look like any of the major libraries have implemented support. Some examples:

[custom-related-posts title=”You may Also Like:” none_text=”None found” order_by=”title” order=”ASC”]

Leave a Comment