原生js實現圖片懶加載

圖片懶加載的基本原理

  1. DOM結構中的img標籤的src屬性默認爲空
  2. img標籤中使用一個自定義屬性(例如data-src)保存圖片的路徑
  3. 當頁面滾動到圖片(img)底部時將自定義屬性(data-src)中的圖片路徑填入src的屬性中

效果圖

js原生實現單張圖片懶加載

代碼的基本原理

HTML結構與樣式

<style> * { margin: 0; padding: 0; } .container { width: 960px; margin: 500px auto 0; text-align: center; } .container .img-box { width: 500px; height: 667px; margin: 0 auto; overflow: hidden; background-color: #aaaaaa; // 做爲佔位圖 margin-bottom: 20px; } </style>
  <div class="container">
    <div class="img-box">
      <img src="" data-src="https://images.pexels.com/photos/2755165/pexels-photo-2755165.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500">
    </div>
  </div>
複製代碼

javascript代碼javascript

window.onload = function () {
  const imgBox = document.querySelector('.img-box')
  const img = document.querySelector('.img-box img')
  window.onscroll = function () {
    // 已經將src填入就再也不須要執行設置src值的代碼
    if (img.getAttribute('src')) {
      return true
    }

    let A = imgBox.offsetTop + imgBox.clientHeight
    let B = window.innerHeight + window.scrollY
    if (B > A) {
      const dataSrc = img.getAttribute('data-src')
      img.setAttribute('src', dataSrc)
    }
  }
}
複製代碼

js實現多張圖片的懶加載

// 假數據
window.onload = function () {
  const container = document.querySelector('.container')
  const imgBox = document.querySelector('.img-box')
  new Array(10).fill(null).forEach(el => {
    const node = imgBox.cloneNode(true)
    container.appendChild(node)
  })
}

window.onscroll = function () {
  const imgBoxes = [...document.querySelectorAll('.img-box')]
  imgBoxes.forEach((el) => {
    lazyLoad(el, el.firstElementChild)
  })
}

// 懶加載函數
/** * * @param {*圖片容器} imgWrapperNode * @param {*圖片} imgNode */
function lazyLoad (imgWrapperNode, imgNode) {
  if (imgNode.getAttribute('src')) {
    return true
  }
  let A = imgWrapperNode.offsetTop + imgWrapperNode.clientHeight
  let B = window.innerHeight + window.scrollY
  if (B > A) {
    const dataSrc = imgNode.getAttribute('data-src')
    imgNode.setAttribute('src', dataSrc)
  }
}
複製代碼

最後附上代碼
html
jshtml

相關文章
相關標籤/搜索