Skip to content

Instantly share code, notes, and snippets.

@sndrs
Last active August 27, 2015 13:01
Show Gist options
  • Save sndrs/855eefd089c51d076c74 to your computer and use it in GitHub Desktop.
Save sndrs/855eefd089c51d076c74 to your computer and use it in GitHub Desktop.
Throttle native browser events to the next animationFrame, mainly to calm 3rd party scripts down
<!DOCTYPE html>
<html>
<head>
<script>
(function (window, Window) {
var eventTypes = ['scroll', 'mousemove', 'touchmove'],
eventTypesRegex = new RegExp(eventTypes.join("|"));
eventTypes.forEach(function (type) {
var running = false;
var throttledEvent = new Event('throttled:' + type);
window.addEventListener(type, function () {
if (!running) {
running = true;
requestAnimationFrame(function () {
window.dispatchEvent(throttledEvent);
running = false;
});
}
});
});
var addEventListenerPrototype = Window.prototype.addEventListener;
Window.prototype.addEventListener = function (type, fn, capture) {
if (eventTypesRegex.test(type)) {
console.log('Hijacking event listener: ' + type);
type = 'throttled:' + type;
}
addEventListenerPrototype(type, fn, capture);
};
})(window, Window);
window.addEventListener('scroll', function (e) {
console.log('scroll event cb, event is: ' + e.type);
});
window.addEventListener('click', function (e) {
console.log('click event cb, event is: ' + e.type);
});
</script>
</head>
<body>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment