0
# Event Utilities
1
2
Event handling utilities for detecting and configuring passive event listeners to improve scroll performance.
3
4
## Capabilities
5
6
### Passive Event Listener Detection
7
8
Determine whether the current browser supports passive event listeners and return appropriate options.
9
10
```typescript { .api }
11
/**
12
* Determine whether the current browser supports passive event listeners, and if so, use them
13
* @param globalObj - The global window object to test against (defaults to window)
14
* @returns {passive: true} if passive listeners are supported, false otherwise
15
*/
16
function applyPassive(globalObj?: Window): boolean | EventListenerOptions;
17
```
18
19
**Usage Examples:**
20
21
```typescript
22
import { applyPassive } from '@material/dom/events';
23
24
// Apply passive listeners for scroll events
25
const passiveOptions = applyPassive();
26
element.addEventListener('touchstart', handler, passiveOptions);
27
element.addEventListener('touchmove', handler, passiveOptions);
28
element.addEventListener('wheel', handler, passiveOptions);
29
30
// Use with custom window object (for testing or iframe contexts)
31
const iframeWindow = iframe.contentWindow;
32
const iframePassiveOptions = applyPassive(iframeWindow);
33
iframeElement.addEventListener('scroll', handler, iframePassiveOptions);
34
```
35
36
## Passive Event Listeners
37
38
Passive event listeners are a web standard that improves scrolling performance by telling the browser that the event handler will not call `preventDefault()`. This allows the browser to process scrolling immediately without waiting for JavaScript execution.
39
40
### Benefits
41
42
- **Improved scroll performance**: Browser can start scrolling immediately
43
- **Better user experience**: Reduces jank and improves responsiveness
44
- **Battery life**: Less CPU usage on mobile devices
45
- **Backward compatibility**: Gracefully falls back to standard listeners
46
47
### When to Use
48
49
Use passive listeners for events where you:
50
- Monitor scrolling or touch events
51
- Don't need to prevent default behavior
52
- Want optimal performance (especially on mobile)
53
54
Common events that benefit from passive listeners:
55
- `touchstart`
56
- `touchmove`
57
- `wheel`
58
- `scroll`
59
60
### Browser Support
61
62
The function automatically detects support for passive listeners and returns:
63
- `{passive: true}` - Modern browsers with passive listener support
64
- `false` - Older browsers that don't support passive listeners
65
66
This ensures your code works consistently across all browsers while taking advantage of performance improvements when available.