Created
May 10, 2021 17:50
-
-
Save Bound3R/83a345b6c4b5b1e9761dbbff9fd3d259 to your computer and use it in GitHub Desktop.
Vanilla Lazyload
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
// 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