Last active
August 27, 2015 13:01
-
-
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
This file contains 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
<!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