What is detect-passive-events?
The detect-passive-events npm package is a utility that helps developers determine if the browser supports passive event listeners. Passive event listeners can improve scrolling performance by letting the browser know that the event listener will not call preventDefault(), allowing the browser to optimize scrolling performance.
What are detect-passive-events's main functionalities?
Detect Passive Event Support
This feature allows you to check if the browser supports passive event listeners. The code sample demonstrates how to use the detect-passive-events package to log whether passive event listeners are supported.
const detectPassiveEvents = require('detect-passive-events');
if (detectPassiveEvents.hasSupport) {
console.log('Passive event listeners are supported.');
} else {
console.log('Passive event listeners are not supported.');
}
Other packages similar to detect-passive-events
detect-it
The detect-it package provides a broader range of detection capabilities, including touch support, pointer events, and passive event listeners. It offers a more comprehensive solution for detecting various input capabilities and event listener support compared to detect-passive-events.
modernizr
Modernizr is a well-known feature detection library that can detect a wide range of HTML5 and CSS3 features, including passive event listener support. It is more extensive and can be used to detect many other features beyond just passive event listeners.
Detect Passive Events
Detects if the browser supports passive event listeners. Tree-shakable and side-effect free. Also available as part of detect-it
.
Live detection test
Note that the code used in the detection is adapted from this Passive Events Explainer.
Using detect-passive-events
npm install --save detect-passive-events
import { supportsPassiveEvents } from 'detect-passive-events';
if (supportsPassiveEvents) {
document.addEventListener('scroll', handleScroll, { capture: false, passive: true });
} else {
document.addEventListener('scroll', handleScroll, false);
}
Or use the script directly in the browser
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.
<script src="https://unpkg.com/detect-passive-events/dist/detect-passive-events.umd.production.js"></script>
if (window.DetectPassiveEvents.supportsPassiveEvents) {
document.addEventListener('scroll', handleScroll, { capture: false, passive: true });
} else {
document.addEventListener('scroll', handleScroll, false);
}