Skip to content

Instantly share code, notes, and snippets.

@leroyrosales
Created April 14, 2020 15:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leroyrosales/f8312f2fbbc8b7b3ea2b155ec2d37813 to your computer and use it in GitHub Desktop.
Save leroyrosales/f8312f2fbbc8b7b3ea2b155ec2d37813 to your computer and use it in GitHub Desktop.
// Lazy Load images w/ IntersectionObserver
let lazyImages = [].slice.call(document.querySelectorAll("img"));
let active = false;
const lazyLoadImages = () => {
if (active === false) {
active = true;
lazyImages.forEach((lazyImage) => {
if ((lazyImage.getBoundingClientRect().top <= window.innerHeight && lazyImage.getBoundingClientRect().bottom >= 0) && getComputedStyle(lazyImage).display !== "none") {
lazyImage.src = lazyImage.src;
lazyImage.srcset = lazyImage.srcset;
lazyImages = lazyImages.filter((image) => {
return image !== lazyImage;
});
if (lazyImages.length === 0) {
document.removeEventListener("scroll", lazyLoadImages);
window.removeEventListener("resize", lazyLoadImages);
window.removeEventListener("orientationchange", lazyLoadImages);
}
}
});
active = false;
}
};
document.addEventListener("scroll", lazyLoadImages);
window.addEventListener("resize", lazyLoadImages);
window.addEventListener("orientationchange", lazyLoadImages);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment