Skip to content

Commit da1b492

Browse files
committed
feat(*): use passive event listeners for better performance
1 parent 55fdc45 commit da1b492

File tree

2 files changed

+26
-3
lines changed

2 files changed

+26
-3
lines changed

lib/ViewportProvider.tsx

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,9 @@ import {
77
shallowEqualScroll,
88
shallowEqualPrivateScroll,
99
shallowEqualDimensions,
10+
browserSupportsPassiveEvents,
1011
} from './utils';
12+
1113
import {
1214
IDimensions,
1315
IPrivateScroll,
@@ -159,9 +161,10 @@ export default class ViewportProvider extends React.PureComponent {
159161
}
160162

161163
componentDidMount() {
162-
window.addEventListener('scroll', this.handleScroll, false);
163-
window.addEventListener('resize', this.handleResize, false);
164-
window.addEventListener('orientationchange', this.handleResize, false);
164+
const options = browserSupportsPassiveEvents ? { passive: true } : false;
165+
window.addEventListener('scroll', this.handleScroll, options);
166+
window.addEventListener('resize', this.handleResize, options);
167+
window.addEventListener('orientationchange', this.handleResize, options);
165168

166169
this.tickId = raf(this.tick);
167170
}

lib/utils.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,3 +59,23 @@ export const shallowEqualDimensions = (a: IDimensions, b: IDimensions) => {
5959

6060
return a.width === b.width && a.height === b.height;
6161
};
62+
63+
// implementation based on https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md
64+
export const browserSupportsPassiveEvents = (() => {
65+
if (typeof window === 'undefined') {
66+
return false;
67+
}
68+
let supportsPassive = false;
69+
try {
70+
var opts = Object.defineProperty({}, 'passive', {
71+
get: () => {
72+
supportsPassive = true;
73+
},
74+
});
75+
window.addEventListener('testPassive', null as any, opts);
76+
window.removeEventListener('testPassive', null as any, opts);
77+
} catch (e) {
78+
return false;
79+
}
80+
return supportsPassive;
81+
})();

0 commit comments

Comments
 (0)