Skip to content

Instantly share code, notes, and snippets.

@Bound3R
Created May 10, 2021 17:50
Show Gist options
  • Save Bound3R/83a345b6c4b5b1e9761dbbff9fd3d259 to your computer and use it in GitHub Desktop.
Save Bound3R/83a345b6c4b5b1e9761dbbff9fd3d259 to your computer and use it in GitHub Desktop.
Vanilla Lazyload
// Progressive loading images
const imagesToLoad = document.querySelectorAll("img[data-src]");
const loadImages = (image) => {
image.setAttribute("src", image.getAttribute("data-src"));
image.onload = () => {
image.removeAttribute("data-src");
};
};
if ("IntersectionObserver" in window) {
const observer = new IntersectionObserver((items) => {
items.forEach((item) => {
if (item.isIntersecting) {
loadImages(item.target);
observer.unobserve(item.target);
}
});
});
imagesToLoad.forEach((img) => {
observer.observe(img);
});
} else {
imagesToLoad.forEach((img) => {
loadImages(img);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment