前端 JS 设置图片懒加载

 

export function setImagesLazyLoad() {
  const pageHeight =
    window.innerHeight ||
    document.documentElement.clientHeight ||
    document.body.clientHeight
  const images = document.getElementsByTagName('img')
  for (let i = 0; i < images.length; i++) {
    const item = images[i]
    const { top } = item.getBoundingClientRect()
    if (top > 0 && top < pageHeight + 50) {
      if (!item.getAttribute('src')) {
        item.setAttribute('src', item.getAttribute('data-url'))
      }
    }
  }
}

export function init() {
// 初始化需要执行一下 init 即可
  setImagesLazyLoad()
  window.addEventListener('pageshow', setImagesLazyLoad)
  window.addEventListener('scroll', setImagesLazyLoad)
  window.addEventListener('hashchange', setImagesLazyLoad)
  window.addEventListener('popstate', setImagesLazyLoad)
}

你可能感兴趣的:(javascript,vue.js,react.js)