前端实现图片懒加载的几种方式

1、基于原生JS中的IntersectionObserver对象实现的图片懒加载

基本思想:

  1. 把图片地址先存入到data-src这个自定义属性中,并且不设置img元素的src属性。
  2. 当监听到img元素出现在视口中了,将该img的data-src属性赋值给src属性,实现
    懒加载。
    实例如下所示:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    <body>
    <div>
    <img alt="loading..." data-src="rand0.jpg">
    </div>
    <div>
    <img alt="loading..." data-src="rand1.jpg">
    </div>
    <div>
    <img alt="loading..." data-src="rand2.jpg">
    </div>
    <div>
    <img alt="loading..." data-src="rand3.jpg">
    </div>
    </body>
    <script>
    // IntersectionObserver实例可以自动观察元素是否在视口内
    var io = new IntersectionObserver(function(ioes) {
    // 遍历观察对象数组(img对象)
    ioes.forEach(function(ioe) {
    // 获得被观察的目标元素,是一个 DOM 节点对象
    var el = ioe.target;
    // 获得目标元素的可见比例,完全可见时为1,完全不可见时小于等于0
    var intersectionRatio = ioe.intersectionRatio;
    if (intersectionRatio > 0 && intersectionRatio <= 1) {
    loadImg(el);
    }
    });
    el.onload = el.onerror = function(){
    io.unobserve(el);
    };
    });
    /**
    * 检查图片是否在窗口内
    * @author yijin
    */
    (function checkImgs() {
    // 获得所有的img元素列表,返回对象是NodeList
    var imgs = document.querySelectorAll("img");
    // 遍历img元素列表,监听每一个img元素
    imgs.forEach(function(item) {
    // 开始观察
    io.observe(item);
    });
    }());
    /**
    * 加载图片
    * @param el 传入的元素对象
    * @author yijin
    */
    function loadImg(el) {
    if (!el.src) {
    var source = el.dataset.src;
    el.src = source;
    }
    }
    </script>