简体   繁体   中英

How to lazy load images using intersection observer?

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);
})

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 class="space"></div> <img alt="I'm lazy" data-src="https://images.dog.ceo/breeds/pug/n02110958_7255.jpg" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM