Skip to content

Commit

Permalink
fix: Use passive event listeners for touchstart/touchmove (#4440)
Browse files Browse the repository at this point in the history
If passive event listening is supported, we should use it.

Fixes #4432.
  • Loading branch information
mister-ben authored and gkatsev committed Jun 28, 2017
1 parent b636663 commit b4dc4f8
Showing 1 changed file with 34 additions and 1 deletion.
35 changes: 34 additions & 1 deletion src/js/utils/events.js
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,33 @@ export function fixEvent(event) {
return event;
}

/**
* Whether passive event listeners are supported
*/
let _supportsPassive = false;

(function() {
try {
const opts = Object.defineProperty({}, 'passive', {
get() {
_supportsPassive = true;
}
});

window.addEventListener('test', null, opts);
} catch (e) {
// disregard
}
})();

/**
* Touch events Chrome expects to be passive
*/
const passiveEvents = [
'touchstart',
'touchmove'
];

/**
* Add an event listener to element
* It stores the handler function in a separate cache object
Expand Down Expand Up @@ -273,7 +300,13 @@ export function on(elem, type, fn) {

if (data.handlers[type].length === 1) {
if (elem.addEventListener) {
elem.addEventListener(type, data.dispatcher, false);
let options = false;

if (_supportsPassive &&
passiveEvents.indexOf(type) > -1) {
options = {passive: true};
}
elem.addEventListener(type, data.dispatcher, options);
} else if (elem.attachEvent) {
elem.attachEvent('on' + type, data.dispatcher);
}
Expand Down

0 comments on commit b4dc4f8

Please sign in to comment.