Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if I don't test Passive event listeners support?

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?

like image 791
Augustin Riedinger Avatar asked May 17 '18 14:05

Augustin Riedinger


People also ask

Does not use passive listeners to improve scrolling performance How do you fix?

To fix this audit, add a passive: true flag to every event listener flagged by GTmetrix. For example, document. addEventListener('touchstart', onTouchStart, {passive: true});

What is a passive event listener?

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?

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.


1 Answers

{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);
like image 131
DigitalDan Avatar answered Oct 04 '22 20:10

DigitalDan