Skip to content

Instantly share code, notes, and snippets.

@floster
Created June 3, 2019 08:44
Show Gist options
  • Save floster/1e8043f24b9432c52e338391b7a5c122 to your computer and use it in GitHub Desktop.
Save floster/1e8043f24b9432c52e338391b7a5c122 to your computer and use it in GitHub Desktop.
Images lazy loading with intersectionObserver API
<script>
document.addEventListener("DOMContentLoaded", function() {
const imageObserver = new IntersectionObserver((entries, imgObserver) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
const lazyImage = entry.target
console.log("lazy loading ", lazyImage)
lazyImage.src = lazyImage.dataset.src
lazyImage.classList.remove("lzy_img");
imgObserver.unobserve(lazyImage);
}
})
});
const arr = document.querySelectorAll('img.lzy_img')
arr.forEach((v) => {
imageObserver.observe(v);
})
})
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment