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;
}
});
}
});
@sgomes
Copy link

sgomes commented Aug 2, 2019

Can this code ever run on the server? If so, we'll need to make the IntersectionObserver more robust, e.g.
typeof window !== 'undefined' && "IntersectionObserver" in window

@sgomes
Copy link

sgomes commented Aug 2, 2019

.lazy seems like a dangerously short and generic CSS classname to hang such complex behaviour upon. I suggest using something like .js-lazy, at the very least, to make it clear it's a CSS class that serves as a JS signal. The alternative is to use a data attribute instead, since you're already relying on them for storing the URL data. That would make the query look like e.g. img[data-lazy].

@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