Created
June 3, 2019 08:44
-
-
Save floster/1e8043f24b9432c52e338391b7a5c122 to your computer and use it in GitHub Desktop.
Images lazy loading with intersectionObserver API
This file contains hidden or 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
<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