detect-passive-events
Version:
Detect if the browser supports passive events
52 lines (37 loc) • 2.02 kB
Markdown
if the browser supports passive event listeners. Tree-shakable and side-effect free. Also available as part of [`detect-it`][detectitrepo].
[ ][livedetectiontest]
[](https://www.npmjs.com/package/detect-passive-events) [](https://bundlephobia.com/result?p=detect-passive-events) 
> Note that the code used in the detection is adapted from this [Passive Events Explainer][passiveexplainer].
```
npm install --save detect-passive-events
```
```js
// supportsPassiveEvents is a boolean
import { supportsPassiveEvents } from 'detect-passive-events';
if (supportsPassiveEvents) {
// passive events are supported by the browser
document.addEventListener('scroll', handleScroll, { capture: false, passive: true });
} else {
// passive events are not supported by the browser
document.addEventListener('scroll', handleScroll, false);
}
```
Optionally, instead using `npm install` you can the load the script directly in the browser. A minified UMD version is available from Unpkg for this purpose.
```html
<script src="https://unpkg.com/detect-passive-events@2/dist/detect-passive-events.umd.production.js"></script>
```
```js
// it will be available on the window as DetectPassiveEvents
if (window.DetectPassiveEvents.supportsPassiveEvents) {
document.addEventListener('scroll', handleScroll, { capture: false, passive: true });
} else {
document.addEventListener('scroll', handleScroll, false);
}
```
<!-- links -->
[ ]: https://detect-it.rafgraph.dev
[ ]: https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md
[ ]: https://github.com/rafgraph/detect-it
Detects