A,

Project recently asked for video capture save, view, because the project is on the part of the public security, leading to a day a console will generate a lot of pictures, see the accident image, page a load too much cause all rendering speed is slow, the experience is not good, so based on existing data online and its practice, summarizes its application in project.

Two, achieve the effect

Third, the implementation process

1, first set the img tag SRC as the loading image address, and then add an actual image address as shown below

    <img
        src="./image/loading.jpg"
        alt=""
        data-src="Https://t7.baidu.com/it/u=378254553, & app = 86 & 3884800361 & FM = 79 size = h300 & & g = 4 n & n = 0 f = jpeg? = 1584852523 & t = 9 e0acf70a49bd4f1 the SEC 1c073e02c44159d2"
      />
Copy the code

2, then write window.onload to execute the method, mainly calculate each image from the top viewport position is greater than the height of the window and scrollbar shrinkage height. Finally, promise is used for the asynchronous loading and state judgment of the picture, and lazy loading method is also called when the scroll is monitored.

 window.onload = function() {
      let imgs = document.querySelectorAll('#picList img')
      let getTop = function(e) {
        return e.offsetTop
      }
      let lazyLoadImg = function(picList) {
        let height = window.innerHeight
        let scollHeight =
          document.documentElement.scrollTop || document.body.scrollTop
        let loadProimise = function(path) {
          return new Promise((resolve, reject) => {
            let image = new Image()
            image.src = path
            image.onload = function() {
              resolve()
            }
            image.onerror = function() {
              reject('Image load failed')}}}for (let i = 0; i < picList.length; i++) {
          if (height + scollHeight > getTop(picList[i])) {
            let path = picList[i].getAttribute('data-src')
            console.log(path)
            loadProimise(path)
              .then(() => {
                picList[i].src = path
              })
              .catch(err => {
                console.log(err)
              })
          }
        }
      }
      lazyLoadImg(imgs)
      window.onscroll = function() {
        lazyLoadImg(imgs)
      }
    }
Copy the code

If you need to debug, the source address: git view