Last active
September 12, 2016 21:04
-
-
Save davej/bae0099e2a305ef12de52137f761df56 to your computer and use it in GitHub Desktop.
Performant scroll change listener
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
// Your scroll callback will only be called once per frame and only | |
// when the y-position changes. Good for doing DOM work without causing | |
// unnecessary reflows of the document. | |
function onScrollYChange(callback) { | |
let latestKnownScrollY = 0, ticking = false; | |
const scrollChanged = () => { | |
ticking = false; | |
const currentScrollY = latestKnownScrollY; | |
callback(currentScrollY) | |
} | |
const requestTick = () => { | |
if (!ticking) requestAnimationFrame(scrollChanged); | |
ticking = true; | |
} | |
const scrollListener = () => { | |
latestKnownScrollY = window.scrollY; | |
requestTick(); | |
} | |
window.addEventListener('scroll', scrollListener, false); | |
} | |
// Usage | |
onScrollYChange(yPos => { | |
console.log(yPos) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment