Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JavaScript实现图片懒加载 #102

Open
GGXXMM opened this issue May 2, 2021 · 0 comments
Open

JavaScript实现图片懒加载 #102

GGXXMM opened this issue May 2, 2021 · 0 comments
Labels
⭐️ js js knowledge

Comments

@GGXXMM
Copy link
Owner

GGXXMM commented May 2, 2021

let imgList = [...document.querySelectorAll('img')];
let len = imgList.length;

const lazyLoad = (function(){
  let count = 0;
  return function() {
    let deleteIndexList = [];
    imgList.forEach((img,index)=> {
      let rec = img.getBoundingClientRect();
      if(rec.top < window.innerHeight) {// 元素出现在可视区(window.innerHeight:可视窗口的高度)
        img.src = img.dataset.src; // 将data-src设置成图片src
        deleteIndexList.push(index);
        count++;
        if(count === len) {// 当图片都加载完,移除滚动监听事件
          document.removeEventListener('scroll', lazyLoad)
        }
      }
    })
    imgList = imgList.filter((img, index)=> !deleteIndexList.includes(index))
  }
})()

// 节流函数
const throttle = function(fn, timing = 500) {
  let prev = 0
  return function() {
    let now = +new Date();
    if(now - prev > timing) {
      prev = now;
      fn.apply(this, arguments)
    }
  }
}
// 滚动监听加上节流控制
const _throttle = throttle(lazyLoad)
document.addEventListener('scroll', _throttle)
@GGXXMM GGXXMM added the ⭐️ js js knowledge label Dec 6, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
⭐️ js js knowledge
Projects
None yet
Development

No branches or pull requests

1 participant