Skip to content

Instantly share code, notes, and snippets.

@lsbyerley
Last active October 24, 2020 17:37
Show Gist options
  • Save lsbyerley/51c8f02797ab44955993ab7c0da047d4 to your computer and use it in GitHub Desktop.
Save lsbyerley/51c8f02797ab44955993ab7c0da047d4 to your computer and use it in GitHub Desktop.
Lazy loading images function. Use Intersection Observer API if available, if not, fallback to the method involving event listeners
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.src = image.dataset.src;
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);
}
lazyloadImages = document.querySelectorAll(".lazy");
}, 20);
}
document.addEventListener("scroll", lazyload);
window.addEventListener("resize", lazyload);
window.addEventListener("orientationChange", lazyload);
}
})
@whitsey
Copy link

whitsey commented Oct 24, 2020

Need to add
lazyloadImages = document.querySelectorAll(".lazy"); after line 41 to reset the 'unloaded' images array to avoid checking every single image after they've already loaded every time the page scrolls.

@lsbyerley
Copy link
Author

Need to add
lazyloadImages = document.querySelectorAll(".lazy"); after line 41 to reset the 'unloaded' images array to avoid checking every single image after they've already loaded every time the page scrolls.

Thanks! gist has been updated

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment