Skip to content

Instantly share code, notes, and snippets.

@kodetop
Last active March 30, 2024 17:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kodetop/70bed1478e80eed73ca7baf7b35c869f to your computer and use it in GitHub Desktop.
Save kodetop/70bed1478e80eed73ca7baf7b35c869f to your computer and use it in GitHub Desktop.
Lazy-Loading - JS
document.addEventListener("DOMContentLoaded", function() {
const lazyLoad = function() {
const lazyImages = document.querySelectorAll("img[data-src]");
lazyImages.forEach(img => {
console.log(img.src, img.dataset.src);
if (img.getBoundingClientRect().top <= window.innerHeight
&& img.getBoundingClientRect().bottom >= 0
&& getComputedStyle(img).display !== 'none') {
img.src = img.dataset.src;
img.removeAttribute("data-src");
}
});
};
lazyLoad();
document.addEventListener("scroll", lazyLoad);
window.addEventListener("resize", lazyLoad);
window.addEventListener("orientationchange", lazyLoad);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment