Created
August 22, 2024 13:45
-
-
Save psahni/8c03e01580219a8b7864c9fd23e5fa67 to your computer and use it in GitHub Desktop.
Lazy Load Images
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); | |
}); | |
Author
psahni
commented
Aug 22, 2024
Intersection api
document.addEventListener("DOMContentLoaded", function() {
var lazyloadImages;
if ("IntersectionObserver" in window) {
lazyloadImages = document.querySelectorAll(".lazy");
var imageObserver = new IntersectionObserver(function(entries, observer) {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
var image = entry.target;
image.classList.remove("lazy");
imageObserver.unobserve(image);
}
});
});
lazyloadImages.forEach(function(image) {
imageObserver.observe(image);
});
} else {
var lazyloadThrottleTimeout;
lazyloadImages = document.querySelectorAll(".lazy");
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