原生JS实现图片懒加载效果

383 阅读1分钟

这是我参与8月更文挑战的第9天,活动详情查看:8月更文挑战

涉及知识点:

  1. Node.children:返回指定节点的所有element子节点,即返回节点元素 Node.childNodes:返回指定节点的所有子节点,包括节点元素和文本元素

  2. 可以用getBoundingClientRect() 它可以获得矩形四条边框,对于当前视口左上角的left right top bottom

  3. 对于Internet Explorer、Chrome、Firefox、Opera 以及 Safari: 浏览器高为 window.innerHeight

为什么要懒加载

懒加载是一种网页性能优化的方式,它能极大的提升用户体验。就比如说图片,图片一直是影响网页性能的主要元凶,现在一张图片超过几兆已经是很经常的事了。如果每次进入页面就请求所有的图片资源,那么可能等图片加载出来用户也早就走了。所以,我们需要懒加载,进入页面的时候,只请求可视区域的图片资源。

总结出来就两个点:

  1. 全部加载的话会影响用户体验
  2. 浪费用户的流量,有些用户并不像全部看完,全部加载会耗费大量流量。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>图片懒加载</title>
    <style>
        .container{
            width: 800px;
            margin: 600px auto;
        }
        .imageBox{
            margin-top: 20px;
            width: 100%;
            height: 130px;
        }
        .imgitem{
            float: left;
            width: 218px;
            height: 130px;
            margin-right: 10px;
        }
        img{
            display: none;
            width: 218px;
        }
    </style>
</head>
<body>

<div class="container">
    <div class="imageBox">
        <div class="imgitem"><img src="" alt="" data-img="image/pro2.png"></div>
        <div class="imgitem"><img src="" alt="" data-img="image/pro3.png"></div>
        <div class="imgitem"><img src="" alt="" data-img="image/pro4.png"></div>
    </div>
    <div class="imageBox">
        <div class="imgitem"><img src="" alt="" data-img="image/pro2.png"></div>
        <div class="imgitem"><img src="" alt="" data-img="image/pro3.png"></div>
        <div class="imgitem"><img src="" alt="" data-img="image/pro4.png"></div>
    </div>

</div>
</body>

<script>

    function show() {

        var $imageBox = document.getElementsByClassName('imageBox'),
            windowLength = window.innerHeight + document.documentElement.scrollTop;
        for(let i=0; i<$imageBox.length; i++){
      
            let imgLength = $imageBox[i].offsetHeight+$imageBox[i].offsetTop;
          
            if (imgLength<=windowLength && $imageBox[i].getAttribute('isLoad') !== 'true'){
               
                $imageBox[i].setAttribute('isLoad','true');
                let $imgItemBox = $imageBox[i].children;
                // console.log($img.src)
                for(let j=0; j<$imgItemBox.length; j++){
                    let $img = $imgItemBox[j].children;
                   
                    $img[0].setAttribute('src',$img[0].getAttribute('data-img'));
                    $img[0].onload = function () {
                        $img[0].style.display = 'block';
                        $img[0].setAttribute('isLoad','true');
                    }

                }

            }
        }
    }

    window.onload = function () {
        show();
    }
    window.onscroll = function () {
        show()
    }

</script>
</html>

总结:

原生总的来说还是比较的复杂,因为有更多的dom操作,但是熟悉这个也可以帮我们更好的理解js,所以 干起来吧朋友