Skip to content

Instantly share code, notes, and snippets.

@harshvats2000
Created November 21, 2020 06:56
Show Gist options
  • Save harshvats2000/f95f61ae9a05526994e7064b08bf5984 to your computer and use it in GitHub Desktop.
Save harshvats2000/f95f61ae9a05526994e7064b08bf5984 to your computer and use it in GitHub Desktop.
document.addEventListener('DOMContentLoaded', function () {
var lazyloadImages = document.querySelectorAll('img.lazy');
var lazyloadThrottleTimeout;
function lazyload() {
if (lazyloadThrottleTimeout) {
clearTimeout(lazyloadThrottleTimeout);
}
lazyloadThrottleTimeout = setTimeout(function () {
var scrollTop = window.pageYOffset;
lazyloadImages.forEach(function (img) {
if (img.offsetTop < window.innerHeight + scrollTop) {
img.src = img.dataset.src;
img.classList.remove('lazy');
}
});
if (lazyloadImages.length == 0) {
document.removeEventListener('scroll', lazyload);
window.removeEventListener('resize', lazyload);
window.removeEventListener('orientationChange', lazyload);
}
}, 20);
}
document.addEventListener('scroll', lazyload);
window.addEventListener('resize', lazyload);
window.addEventListener('orientationChange', lazyload);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment