简体   繁体   English

如何使用交叉点观察器延迟加载图像?

[英]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.您可以将实际图像源设置为数据属性,并在图像与视口相交时将其设置回src

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" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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