Created
September 16, 2019 09:23
-
-
Save yastrebovb/05fc72c01e9a4357376dfc7883bf8c82 to your computer and use it in GitHub Desktop.
Passive event listeners for lighthouse "Best Practices"
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function() { | |
var supportsPassive = eventListenerOptionsSupported(); | |
if (supportsPassive) { | |
var addEvent = EventTarget.prototype.addEventListener; | |
overwriteAddEvent(addEvent); | |
} | |
function overwriteAddEvent(superMethod) { | |
var defaultOptions = { | |
passive: true, | |
capture: false | |
}; | |
EventTarget.prototype.addEventListener = function(type, listener, options) { | |
var usesListenerOptions = typeof options === 'object'; | |
var useCapture = usesListenerOptions ? options.capture : options; | |
options = usesListenerOptions ? options : {}; | |
options.passive = options.passive !== undefined ? options.passive : defaultOptions.passive; | |
options.capture = useCapture !== undefined ? useCapture : defaultOptions.capture; | |
superMethod.call(this, type, listener, options); | |
}; | |
} | |
function eventListenerOptionsSupported() { | |
var supported = false; | |
try { | |
var opts = Object.defineProperty({}, 'passive', { | |
get: function() { | |
supported = true; | |
} | |
}); | |
window.addEventListener("test", null, opts); | |
} catch (e) {} | |
return supported; | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment