Skip to content

Instantly share code, notes, and snippets.

@MWarCZ
Last active February 6, 2022 14:30
Show Gist options
  • Save MWarCZ/e14f8bf1478c076b8f4e59806918c1d4 to your computer and use it in GitHub Desktop.
Save MWarCZ/e14f8bf1478c076b8f4e59806918c1d4 to your computer and use it in GitHub Desktop.
Lazy loading scripts after the first user interaction with the site.
// Source: https://marketingmakers.net/en/how-to-improve-zopim-zendesk-chat-load-time-or-any-other-external-javascript/
// Lazy loading scripts after the first user interaction with the site
function setupInteractLoad(fn) {
function fn_tmp() {
destroyInteractLoadEvent(fn_tmp);
fn();
}
createInteractLoadEvent(fn_tmp);
}
// Setting up triggers for user interaction with site
function createInteractLoadEvent(fn) {
document.addEventListener('scroll', fn);
document.addEventListener('mousedown', fn);
document.addEventListener('mousemove', fn);
document.addEventListener('touchstart', fn);
document.addEventListener('keydown', fn);
}
// Delete triggers for user interaction with site
function destroyInteractLoadEvent(fn) {
document.removeEventListener('scroll', fn);
document.removeEventListener('mousedown', fn);
document.removeEventListener('mousemove', fn);
document.removeEventListener('touchstart', fn);
document.removeEventListener('keydown', fn);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment