Chromium gives me a warning about my event listener not being passive.
Fine.
I'm not going to use event.preventDefault()
there so I am willing to make it passive.
But then when I read the detailed explanation, the example uses Modernizr to check if the attribute is available.
addEventListener(document, "touchstart", function(e) {
}, Modernizr.passiveeventlisteners ? {passive: true} : false);
But I don't have Modernizr installed, and I find a pain to set it up for this very specific use case.
So the question is: what happens if I blindly write:
$el.addEventListener('touchstart', () => {}, {passive: true})
?
in old browsers?
My guess is that the object might be evaluated to true
, is that correct? No error to be risen?
To fix this audit, add a passive: true flag to every event listener flagged by GTmetrix. For example, document. addEventListener('touchstart', onTouchStart, {passive: true});
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.
How the Lighthouse passive event listener audit fails # Lighthouse uses the following process to identify event listeners that may affect scrolling performance: Collect all event listeners on the page. Filter out non-touch and non-wheel listeners.
{passive: true}
will be evaluated as true
so that should get rid of the Chromium warning, but according to the link you provided, it could have "unforseen results" on older browsers.
This method (also suggested in that link) seems pretty good to me, and it doesn't need any other libraries:
// Test via a getter in the options object to see if the passive property is accessed
var supportsPassive = false;
try {
var opts = Object.defineProperty({}, 'passive', {
get: function() {
supportsPassive = true;
}
});
window.addEventListener("testPassive", null, opts);
window.removeEventListener("testPassive", null, opts);
} catch (e) {}
// Use our detect's results. passive applied if supported, capture will be false either way.
elem.addEventListener('touchstart', fn, supportsPassive ? { passive: true } : false);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With