This is the original

This is a translation

This is the Chromium Blog

The vernacular

In layman’s terms, passive event listeners are an optimization for the mobile scrolling experience.

(The touchStart and TouchMove mentioned below are both bound to document)

Let’s first look at what happens to kidneys in the next scroll:

As you can see, the scrolling behavior is blocked.

This is because the TouchStart and TouchMove preventDefault prevent this scrolling behavior. The browser doesn’t know whether the callback has preventDefault at first, so it has to wait for the callback to complete.

Then Chrome did a survey and found that 80% of sites that had registered TouchStart and TouchMove didn’t prevent scrolling, and 10% of those 80% cases delayed the start of scrolling by more than 100ms, and 1% of those cases had catastrophic delays of more than 500ms.

Passive was created because the browser would know if it would block scrolling.

Passive use

Passive is dependent on the addEventListener, and many people only know that the third argument is useCapture. Let’s look at the documentation again and see:

target.addEventListener(type, listener [, options]);

target.addEventListener(type, listener [, useCapture]);

target.addEventListener(type, listener [, useCapture, wantsUntrusted This API has not been standardized. ]);

The first is the one we need to talk about here. Options Provides three parameters: Capture once passive.

Passive Whether to enable passive event listener. If true, the callback will not call preventDefault(). If it does, it will not take effect and will generate a warning.

Some browsers (notably Chrome and Firefox) have changed the default value of the Passive option for the TouchStart and TouchMove events on the Document level nodes Window, Document, and Document.body to true

Compares processes after passive is enabled

Did not open

Has been open

compatibility

Chrome 51+ Edge 18+ Firfox IE incompatible

There’s a polyfill given by MDN

let passiveIfSupported = false;

try {
  window.addEventListener("test".null.Object.defineProperty(
      {},
      "passive",
      {
        get: function() { passiveIfSupported = { passive: true}; }})); }catch(err) {}

window.addEventListener('scroll'.function(event) {
  /* do something */
  // can't use event.preventDefault();
}, passiveIfSupported );

Copy the code