Created
September 1, 2015 04:15
-
-
Save sheniff/fca5488908b74cb70d60 to your computer and use it in GitHub Desktop.
Throttled, efficient scroll that only runs once per frame redraw (From MDN documentation https://developer.mozilla.org/en-US/docs/Web/Events/scroll)
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 throttle = function(type, name, obj) { | |
| var obj = obj || window; | |
| var running = false; | |
| var func = function() { | |
| if (running) { return; } | |
| running = true; | |
| requestAnimationFrame(function() { | |
| obj.dispatchEvent(new CustomEvent(name)); | |
| running = false; | |
| }); | |
| }; | |
| // Original event is tied to a func that'll only trigger once every animation frame | |
| obj.addEventListener(type, func); | |
| }; | |
| /* init - you can init any event */ | |
| throttle ("scroll", "optimizedScroll"); | |
| })(); | |
| // handle event | |
| window.addEventListener("optimizedScroll", function() { | |
| console.log("Resource conscious scroll callback!"); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment