How can I enable passive listeners to improve scrolling performance?

Hey folks, I hope you’re all well.

Web.dev is returning a “Does not use passive listeners to improve scrolling performance” message which I’d like to get rid of.

The line it references can be seen in bold below.

// js/mixin/vertical-scroll-blocker.js
var VerticalScrollBlockerMixin = {
_blockVerticalScroll(threshold = 18) {
this.addEventListener(“touchstart”, (event) => {
this.firstTouchClientX = event.touches[0].clientX;
});
this.addEventListener(“touchmove”, (event) => {
const touchClientX = event.touches[0].clientX - this.firstTouchClientX;
if (Math.abs(touchClientX) > threshold) {
event.preventDefault();
}
}, { passive: true });
}
};

I can’t for the life of me figure out how to enable that specific line as passive. some assistance would be lovely!

Thanks so much,

Dave

Hi Dave, nice to meet you! Great question, you nearly have it done here, you simply need to add the passive flag for all event listeners that Lighthouse has detected, which you have done for the second event but not the first event listener - e.g

this.addEventListener("touchstart", (event) => {
this.firstTouchClientX = event.touches[0].clientX;
}, {passive: true});

So your whole code snippet would look like this:

var VerticalScrollBlockerMixin = {
_blockVerticalScroll(threshold = 18) {
this.addEventListener("touchstart", (event) => {
this.firstTouchClientX = event.touches[0].clientX;
}, {passive: true});

this.addEventListener("touchmove", (event) => {
const touchClientX = event.touches[0].clientX - this.firstTouchClientX;
if (Math.abs(touchClientX) > threshold) {
event.preventDefault();
}
}, { passive: true });

}
};

Here’s the reference for more info: https://web.dev/uses-passive-event-listeners/

If you require further assistance on optimizing your store and obtaining a higher pagespeed grade from Google’s Pagespeed insights our team specializes in these tasks and can help ensure your store is as fast as possible. We can do theme modifications, lazy loading apps, conditional loading and work on your core vitals - or as you are more DIY minded we can simply audit and provide you with advisories and a detailed overview so you can take it from there.

Send a DM or contact us for more information. You can also use our free Shopify Analyzer service to garner more information on your page’s elements performance.

1 Like

Ah! I love you! This worked an absolute treat - thank you SO much!

I am trying to fix this same issue. Where do I add and fix this at in my code?