# 懒加载

# 图片懒加载

function lazyload() {
  let viewHeight = document.body.clientHeight //获取可视区高度
  let imgs = document.querySelectorAll('img[data-src]')
  imgs.forEach((item, index) => {
    if (item.dataset.src === '') return

    // 用于获得页面中某个元素的左,上,右和下分别相对浏览器视窗的位置
    let rect = item.getBoundingClientRect()
    if (rect.bottom >= 0 && rect.top < viewHeight) {
      item.src = item.dataset.src
      item.removeAttribute('data-src')
    }
  })
}

window.addEventListener('scroll', throttle(lazyload, 200))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
上次更新: 2022-11-29 16:59:20(UTC +8)