Demo

The HTML code

<! DOCTYPE html> <html lang="zh">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    *{
      padding: 0;
      margin: 0;
    }
    img{
      display: block;
      margin-bottom: 10px;
      width: 100%;
      min-height: 300px
    }
  </style>
</head>
<body>
  <div class="image-list">
    <img src="" alt="" class="image-item" lazyload="true" data-original="https://i.pinimg.com/564x/42/e3/62/42e362eefa411bc38c99e4685d209f42.jpg">
    <img src="" alt="" class="image-item" lazyload="true" data-original="https://i.pinimg.com/564x/d7/56/6e/d7566e31a118fb5813906fbe3cdd66be.jpg">
    <img src="" alt="" class="image-item" lazyload="true" data-original="https://i.pinimg.com/564x/4a/a7/70/4aa7709f4bdb29c7602dd4f8ef89231b.jpg">
    <img src="" alt="" class="image-item" lazyload="true" data-original="https://i.pinimg.com/564x/50/75/29/507529c946d31c97a944de25d0089b96.jpg">
    <img src="" alt="" class="image-item" lazyload="true" data-original="https://i.pinimg.com/564x/6f/d3/ab/6fd3abdcd29b5843e15a759d286c4cd0.jpg">
    <img src="" alt="" class="image-item" lazyload="true" data-original="https://i.pinimg.com/564x/d3/3a/6f/d33a6f8d2b5020a60edf93cc0afa2be5.jpg">
    <img src="" alt="" class="image-item" lazyload="true" data-original="https://i.pinimg.com/564x/86/41/e1/8641e174555200465cad3df476aa0f38.jpg">
    <img src="" alt="" class="image-item" lazyload="true" data-original="https://i.pinimg.com/564x/bd/5a/e8/bd5ae8503667119d954b6e181a92b99d.jpg">
    <img src="" alt="" class="image-item" lazyload="true" data-original="https://i.pinimg.com/564x/b5/d8/f0/b5d8f0c92f42e5cebd6fdeca6a394668.jpg">
    <img src="" alt="" class="image-item" lazyload="true" data-original="https://i.pinimg.com/564x/e2/7a/64/e27a64a801a115bd7e6a5449c008c203.jpg">
  </div>
  <script src="./index.js"></script>
</body>
</html>
Copy the code

Js code

var viewHeight = document.documentElement.clientHeight;

function lazyload(){
  var eles = document.querySelectorAll('img[data-original][lazyload]');
  Array.prototype.forEach.call(eles,function(item,index){
    var rect
    if(item.dataset.original === ' ') {return
    }
    rect = item.getBoundingClientRect();
    if(rect.bottom>=0&&rect.top<viewHeight){
      !function(){
        var img = new Image();
        img.src = item.dataset.original;
        img.onload = function(){
          item.src = img.src
        };
        item.removeAttribute('data-original');
        item.removeAttribute('lazyload');
      }()
    }
  })
}

lazyload();

document.addEventListener('scroll',lazyload)
Copy the code