Home > Software engineering >  How to lazy load images using intersection observer?
How to lazy load images using intersection observer?

Time:01-16

I have implemented this intersection observer to have images fade in as they enter the viewport. However, when the page is reloaded the images still load in immediately even though they aren't in the viewport. Does intersection observer have the ability to lazy load these images?

JavaScript code:

    'use strict';
    
    
    
    const faders = document.querySelectorAll('.fade-in');
    
    const appearOptions = {
        threshold: 0.4
    
    };
    const appearOnScroll = new IntersectionObserver(function(entries, appearOnScroll) {
        entries.forEach(entry => {
            if (!entry.isIntersecting) return;
            else {
                entry.target.classList.add('appear');
                appearOnScroll.unobserve(entry.target);
    
            }
        })
    }, appearOptions);

faders.forEach(fader => {
    appearOnScroll.observe(fader);
})

CodePudding user response:

You can set the actual image source to a data attribute and set it back to src when the image intersects the viewport.

Run the below snippet and scroll down:

const img = document.querySelector('img');

const io = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if (!entry.isIntersecting) return;
    entry.target.src = entry.target.getAttribute('data-src');
    io.unobserve(entry.target);
  })
});

io.observe(img);
.space {
  height: 100vh;
}
<div ></div>
<img alt="I'm lazy" data-src="https://images.dog.ceo/breeds/pug/n02110958_7255.jpg" />

  •  Tags:  
  • Related