Smashing Magazine has an extensive article on using the aforementioned IntersectionObserver
to lazy load image assets on your page.
The article first explains the difference between a regular Event and an Observer, before diving into the IntersectionObserver
.
const images = document.querySelectorAll('[data-src]');
const config = {
rootMargin: '0px 0px 50px 0px',
threshold: 0
};
let loaded = 0;
let observer = new IntersectionObserver(function (entries, self) {
entries.forEach(entry => {
if (entry.isIntersecting) {
// console.log(`Image ${entry.target.src} is in the viewport!`);
preloadImage(entry.target);
// Stop watching and load the image
self.unobserve(entry.target);
}
});
}, config);
images.forEach(image => {
observer.observe(image);
});
Now You See Me: How To Defer, Lazy-Load And Act With IntersectionObserver
→