While working on the performance of my WP website, I stumbled upon an error stating: "Use passive listeners to improve scrolling performance".
I found this solution to it and that error disappeared, although it was substituted by a new error (Unable to preventDefault inside passive event listener invocation). The current error appears repeatedly and Google's Pagespeed Insights links it to jquery.min.js
, although I'm not sure about the correct way to fix it.
Should I make any changes in the jQuery file? Should I modify the code that fixed the "Use passive listeners..." error (you can see it below)?
EDIT: I located the exact, problematic preventDefault()
and following the advice from Patrick, I simply deleted it and the issue has been solved, my website is now running smoothly.
(function() {
var supportsPassive = eventListenerOptionsSupported();
if (supportsPassive) {
var addEvent = EventTarget.prototype.addEventListener;
overwriteAddEvent(addEvent);
}
function overwriteAddEvent(superMethod) {
var defaultOptions = {
passive: true,
capture: false
};
EventTarget.prototype.addEventListener = function(type, listener, options) {
var usesListenerOptions = typeof options === 'object';
var useCapture = usesListenerOptions ? options.capture : options;
options = usesListenerOptions ? options : {};
options.passive = options.passive !== undefined ? options.passive : defaultOptions.passive;
options.capture = useCapture !== undefined ? useCapture : defaultOptions.capture;
superMethod.call(this, type, listener, options);
};
}
function eventListenerOptionsSupported() {
var supported = false;
try {
var opts = Object.defineProperty({}, 'passive', {
get: function() {
supported = true;
}
});
window.addEventListener("test", null, opts);
} catch (e) {}
return supported;
}
})();
CodePudding user response:
When you use a passive event listener you're making a promise not to use a preventDefault() in that listener to disable scrolling. This frees the browser up to respond to scrolling immediately without waiting for JavaScript. A passive event listener is mainly used in touch start or touch move or wheel listeners. This ensures a reliable smooth scrolling experience, in theory.
So you can either remove the preventDefault() in the event listener or mark the event listener not being passive but I wouldn't recommend that. Try testing what happens when you remove the preventDefault() and in theory, it should work the same
I hope this helps