Created
May 31, 2019 04:54
-
-
Save colelawrence/6c76830696aa6d89bef06483b94ecde0 to your computer and use it in GitHub Desktop.
Passive onscroll event 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
onScroll(window, (scrollX, scrollY) => { | |
log({ scrollX, scrollY }) | |
}) | |
function onScroll(target: HTMLElement, fn) { | |
const onscroll = (_evt) => fn(target.scrollX, target.scrollY); | |
if (supportsPassive()) { | |
target.addEventListener("scroll", onscroll, { passive: true }) | |
} else { | |
let timer | |
addEventListener("scroll", (evt) => { | |
clearTimeout(timer) | |
timer = setTimeout(onscroll.bind(null, evt), 10) | |
}) | |
} | |
} | |
function supportsPassive() { | |
var supportsPassiveOption = false; | |
try { | |
var opts = Object.defineProperty({}, 'passive', { | |
get: function() { | |
supportsPassiveOption = true; | |
} | |
}); | |
window.addEventListener('test', null, opts); | |
} catch (e) {} | |
return supportsPassiveOption; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment