优化响应速度之图片懒加载

74 阅读1分钟

WeChat2229c0dae78d03bb9649fb56546e0af1.png

<img src="img/1pxImg.png" data-url="img/1.jpg">
<img src="img/1pxImg.png" data-url="img/2.jpg">
<img src="img/1pxImg.png" data-url="img/3.jpg">
<img src="img/1pxImg.png" data-url="img/4.jpg">
<img src="img/1pxImg.png" data-url="img/5.jpg">

<script>
    var imgs = document.getElementsByTagName('img')
    // 观察器实例
    let io = new IntersectionObserver((entires) =>{
        entires.forEach(item => {
            // 原图片元素
            let oImg = item.target
            if (item.intersectionRatio > 0 && item.intersectionRatio <= 1) {
                oImg.setAttribute('src', oImg.getAttribute('data-url'))
            } 
        })
    })
   // 给每一个图片设置观察器
    Array.from(imgs).forEach(element => {
        io.observe(element) 
    });
</script>