UNPKG

2.02 kBMarkdownView Raw
1# Detect Passive Events
2
3Detects if the browser supports passive event listeners. Tree-shakable and side-effect free. Also available as part of [`detect-it`][detectitrepo].
4
5[Live detection test][livedetectiontest]
6
7[![npm](https://img.shields.io/npm/dm/detect-passive-events?label=npm)](https://www.npmjs.com/package/detect-passive-events) [![npm bundle size](https://img.shields.io/bundlephobia/minzip/detect-passive-events?color=purple)](https://bundlephobia.com/result?p=detect-passive-events) ![npm type definitions](https://img.shields.io/npm/types/detect-passive-events?color=blue)
8
9> Note that the code used in the detection is adapted from this [Passive Events Explainer][passiveexplainer].
10
11### Using `detect-passive-events`
12
13```
14npm install --save detect-passive-events
15```
16
17```js
18// supportsPassiveEvents is a boolean
19import { supportsPassiveEvents } from 'detect-passive-events';
20
21if (supportsPassiveEvents) {
22 // passive events are supported by the browser
23 document.addEventListener('scroll', handleScroll, { capture: false, passive: true });
24} else {
25 // passive events are not supported by the browser
26 document.addEventListener('scroll', handleScroll, false);
27}
28```
29
30### Or use the script directly in the browser
31
32Optionally, 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.
33
34```html
35<script src="https://unpkg.com/detect-passive-events@2/dist/detect-passive-events.umd.production.js"></script>
36```
37
38```js
39// it will be available on the window as DetectPassiveEvents
40if (window.DetectPassiveEvents.supportsPassiveEvents) {
41 document.addEventListener('scroll', handleScroll, { capture: false, passive: true });
42} else {
43 document.addEventListener('scroll', handleScroll, false);
44}
45```
46
47<!-- links -->
48
49[livedetectiontest]: https://detect-it.rafgraph.dev
50[passiveexplainer]: https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md
51[detectitrepo]: https://github.com/rafgraph/detect-it