图片懒加载

1.HTML原生支持
<img src="example.jpg" alt="示例图片" loading="lazy">
优点:
实现简单,不需要额外js代码
浏览器内部优化、性能较好
缺点:
兼容性问题:部分旧版本浏览器(如IE)不支持。
2.使用IntersectionObserver API
对于需要兼容更多或更灵活控制加载行为的场景,可以使用IntersectionObserver API。它能够监听元素与视窗交叉的状态,从而触发图片加载。需及时解除监控,提升性能

    function Observer() {
        const observer = new IntersectionObserver((entries) => {
            entries.forEach((item, index) => {
                if (item.isIntersecting) {
                    item.target.src = imageList[index].url
                    item.target.classList.remove('lazy')
                    observer.unobserve(item.target)
                }
            })
        })
        const img = document.querySelectorAll('img')
        console.log(img)
        img.forEach(item => {
            observer.observe(item)

        })
    }
    document.addEventListener('DOMContentLoaded', () => {
        Observer()
    })

3.使用第三方工具

posted @ 2025-07-03 20:07  我就起个名字不至于吧  阅读(10)  评论(0)    收藏  举报