/ Gists / Lazy loading with IntersectionObserver
On gists

Lazy loading with IntersectionObserver

JavaScript

image-lazy-loading.js Raw #

document.addEventListener('DOMContentLoaded', () => {
    let lazyImages = document.querySelectorAll('.lazyload');
    let observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                let img = entry.target;
                img.src = img.dataset.src;
                observer.unobserve(img);
            }
        });
    });
    lazyImages.forEach(img => {
        observer.observe(img);
    });
});