Skip to content

Instantly share code, notes, and snippets.

@TerribleDev
Created May 23, 2019 15:16
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 TerribleDev/4c0e45faf4dca080f5a6eac702995e0d to your computer and use it in GitHub Desktop.
Save TerribleDev/4c0e45faf4dca080f5a6eac702995e0d to your computer and use it in GitHub Desktop.
Lazy load images :)
if(window.IntersectionObserver) {
document.addEventListener("DOMContentLoaded", function() {
var lazyImages = [].slice.call(document.querySelectorAll(".lazy"));
var lazyImageObserver = new IntersectionObserver(function(entries, observer) {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
var lazyImage = entry.target;
if(lazyImage.dataset.src) {
lazyImage.src = lazyImage.dataset.src;
}
if(lazyImage.dataset.srcset) {
lazyImage.srcset = lazyImage.dataset.srcset;
}
lazyImage.classList.remove("lazy");
lazyImageObserver.unobserve(lazyImage);
}
});
});
lazyImages.forEach(function(lazyImage) {
lazyImageObserver.observe(lazyImage);
});
});
} else {
var lazyImages = [].slice.call(document.querySelectorAll(".lazy"));
lazyImages.forEach(function(image) {
if(image.dataset.srcset) {
image.srcset = image.dataset.srcset;
}
if(image.dataset.src) {
image.src = image.dataset.src;
}
});
}
@TerribleDev
Copy link
Author

This looks for images with the class of lazy and that have data-src attributes set for their urls. When they are visible to the user the data-src gets put in the src attribute. also works with data-srcset

@TerribleDev
Copy link
Author

P.S. this uses var for ie11, but you can use let if you have babel recompile the code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment