Created
August 28, 2019 19:08
-
-
Save jawakarD/46ba0851f254b21d115648d315aba688 to your computer and use it in GitHub Desktop.
lazy-load-script-medium
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
<script type="text/javascript"> | |
document.addEventListener("DOMContentLoaded", function() { | |
let lazyImages = [].slice.call(document.querySelectorAll("img.lazy")); | |
let active = false; | |
const lazyLoad = function() { | |
if (active === false) { | |
active = true; | |
setTimeout(function() { | |
lazyImages.forEach(function(lazyImage) { | |
if ((lazyImage.getBoundingClientRect().top <= window.innerHeight && lazyImage.getBoundingClientRect().bottom >= 0) && getComputedStyle(lazyImage).display !== "none") { | |
lazyImage.src = lazyImage.dataset.src; | |
lazyImage.srcset = lazyImage.dataset.srcset; | |
lazyImage.classList.remove("lazy"); | |
lazyImages = lazyImages.filter(function(image) { | |
return image !== lazyImage; | |
}); | |
if (lazyImages.length === 0) { | |
document.removeEventListener("scroll", lazyLoad); | |
window.removeEventListener("resize", lazyLoad); | |
window.removeEventListener("orientationchange", lazyLoad); | |
} | |
} | |
}); | |
active = false; | |
}, 200); | |
} | |
}; | |
document.addEventListener("scroll", lazyLoad); | |
window.addEventListener("resize", lazyLoad); | |
window.addEventListener("orientationchange", lazyLoad); | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment