Created
November 21, 2020 06:56
-
-
Save harshvats2000/f95f61ae9a05526994e7064b08bf5984 to your computer and use it in GitHub Desktop.
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
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