Skip to content

Instantly share code, notes, and snippets.

@josephscott
Last active August 3, 2019 02:23
Show Gist options
  • Save josephscott/dce52e612b945dc621c5ce7f182656ea to your computer and use it in GitHub Desktop.
Save josephscott/dce52e612b945dc621c5ce7f182656ea to your computer and use it in GitHub Desktop.
document.addEventListener("DOMContentLoaded", function() {
var lazyImages = [].slice.call(document.getElementsByClassName("js-lazy-img"));
if ("IntersectionObserver" in window) {
var config = {
// If the image gets within 250px of the browser's viewport, start the download:
rootMargin: '250px 0px',
};
var lazyImageObserver = new IntersectionObserver(function(entries, observer) {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
var lazyImage = entry.target;
lazyImage.src = lazyImage.dataset.src;
// Not all images are responsive, sometimes we always serve the original
if (lazyImage.dataset.srcset) {
lazyImage.srcset = lazyImage.dataset.srcset;
}
lazyImageObserver.unobserve(lazyImage);
}
});
}, config);
lazyImages.forEach(function(lazyImage) {
lazyImageObserver.observe(lazyImage);
});
}
else {
// For browsers that don't support IntersectionObserver yet, load all the images now:
lazyImages.forEach(function(lazyImage) {
lazyImage.src = lazyImage.dataset.src;
// Not all images are responsive, sometimes we always serve the original
if (lazyImage.dataset.srcset) {
lazyImage.srcset = lazyImage.dataset.srcset;
}
});
}
});
@josephscott
Copy link
Author

1- No, this should never be running on the server. It needs a view port, and that is entirely client dependent.

2- Fair point on the class name, I'll expand it to something more unique.

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