Skip to content

Instantly share code, notes, and snippets.

@Loonz806
Created March 23, 2020 17:05
Show Gist options
  • Save Loonz806/88ded93c081bc1f15d27b2eb7814ef40 to your computer and use it in GitHub Desktop.
Save Loonz806/88ded93c081bc1f15d27b2eb7814ef40 to your computer and use it in GitHub Desktop.
A defer script execution snippet for only executing a callback on user interaction
function deferStartTillUserAction(cb) {
var locked = true;
var didClick = false;
var didScroll = false;
function unlock() {
if (locked) {
locked = false;
cb();
}
}
function deferMove(_ref) {
unlock();
}
function deferTouch(event) {
if (locked) {
deferMove(event);
var target = event.target; // on iOS links can be not clicked through images
if (!didClick && !didScroll) {
target.click();
}
}
}
function deferScroll(event) {
didScroll = true;
deferMove(event);
}
function deferClick(event) {
didClick = true;
if (locked) {
unlock();
}
}
document.addEventListener("click", deferClick, true);
document.addEventListener("mousemove", deferMove, true);
document.addEventListener("keydown", deferMove, true);
document.addEventListener("touchstart", deferTouch, true);
window.addEventListener("scroll", deferScroll); // TODO: start js if some placeholder (pagination?, lazy image?) is visible
}
deferStartTillUserAction(function () {
//whatever callback you want to execute
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment