JQuery - How to marke touch and wheel event listeners as `passive`

Viewed 3116

I'm using Google Page Speed Insights to optimize my page speed. It tells me to not use passive listeners to improve scrolling performance. I know how to do it with vanilla javascript.

window.addEventListener(
  'scroll',
  () => {
    handleScroll();
  },
  { passive: true }
);

How to do this with JQuery?

enter image description here

1 Answers

This worked for me. Just add it directly after jQuery has been loaded

// Passive event listeners //Two slight variations in setting the flag but seems to accomplish same thing

jQuery.event.special.touchstart = {
    setup: function( _, ns, handle ) {
        this.addEventListener("touchstart", handle, { passive: !ns.includes("noPreventDefault") });
    }
};
jQuery.event.special.touchmove = {
    setup: function( _, ns, handle ) {
        this.addEventListener("touchmove", handle, { passive: !ns.includes("noPreventDefault") });
    }
};
jQuery.event.special.wheel = {
    setup: function( _, ns, handle ){
        this.addEventListener("wheel", handle, { passive: true });
    }
};
jQuery.event.special.mousewheel = {
    setup: function( _, ns, handle ){
        this.addEventListener("mousewheel", handle, { passive: true });
    }
};
Related