使用 IntersectionObserver 实现懒加载

60 阅读1分钟

在vue中实现懒加载,在mounted中使用

const ob = new IntersectionObserver((entries) => {
     entries.forEach((item) => {
        if (item.isIntersecting) {
            const img = item.target
                        img.src = `https://picsum.photos/350/118?r=${Math.random()}`
                        ob.unobserve(img)
            }
        })
    })
    let imgs = document.querySelectorAll('img')
    imgs.forEach((item) => {
        ob.observe(item)
    })
}