Passive Event Listeners & Touch Optimization
Passive Event Listeners & Touch Optimization in Modern JavaScript
Smooth scrolling and touch responsiveness are critical for mobile web applications. A major cause of mobile scroll stutter (jank) is the browser's requirement to check whether an event listener calls event.preventDefault(). Passive Event Listeners eliminate this bottleneck, boosting scroll performance to 60 FPS.
1. The Scroll Delay Problem Explained
When a user places their finger on a mobile screen and swipes:
- 1The browser dispatches a
touchstartortouchmoveevent. - 2The browser does not know if your JavaScript will call
event.preventDefault()(which halts scrolling). - 3Therefore, the browser must pause the main scrolling thread and wait for your JavaScript listener to finish executing!
- 4Even a 50ms JavaScript delay produces noticeable scroll stutter and delays page motion.
2. Enabling Passive Event Listeners
Pass { passive: true } in the options object of addEventListener:
What Happens if you Call preventDefault() in a Passive Listener?
The browser completely ignores the call and logs a console warning:
3. Eliminating the 300ms Mobile Tap Delay
On older mobile browsers, a 300ms delay occurred between a user tapping the screen and the click event firing (as the browser waited to see if the tap was a double-tap to zoom).
Modern Solutions:
- 1Viewport Meta Tag (Standard):
Modern browsers recognize width=device-width and automatically eliminate the 300ms tap delay!
- 1CSS
touch-actionProperty:
4. Feature Detecting Passive Listeners
In legacy environments or custom libraries, feature-detect passive listener support:
Practice Quiz
Pointer Events & Gesture Handling
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Debouncing vs Throttling Deep Dive | Pointer Events & Gesture Handling |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.