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

图片懒加载原理及如何实现 #51

Open
artdong opened this issue Nov 21, 2019 · 1 comment
Open

图片懒加载原理及如何实现 #51

artdong opened this issue Nov 21, 2019 · 1 comment
Labels
js javascript

Comments

@artdong
Copy link
Collaborator

artdong commented Nov 21, 2019

图片懒加载原理及如何实现

@artdong artdong added the js javascript label Nov 21, 2019
@FunnyZ
Copy link
Collaborator

FunnyZ commented Dec 25, 2019

图片懒加载其实就是用一个自定义属性存储图片的src,当且仅当图片出现或进入可视范围才去加载它。
下面是两种方法实现图片懒加载:

/* getBoundClientRect 的实现方式,监听 scroll 事件 */
let imgList = [...document.querySelectorAll('img')];
let num = imgList.length;

let lazyLoad = (function() {
  let count = 0;
  return function() {
    let deleteIndexList = [];
    imgList.forEach((img, index) => {
      let rect = img.getBoundingClientRect();
      if (rect.top < window.innerHeight) {
        img.src = img.dataset.src;
        deleteIndexList.push(index);
        count++;
        if (count === num) {
          document.removeEventListener(
            'scroll',
            lazyLoad
          );
        }
      }
    });
    imgList = imgList.filter(
      (_, index) => !deleteIndexList.includes(index)
    );
  };
})();
/* intersectionObserver 实现方式,实例化一个 IntersectionObserver,并使其观擦所有 img 标签 */
let imgList = [...document.querySelectorAll('img')];

let lazyLoad = function() {
  let observer = new IntersectionObserver(entries => {
    entries.forEach(entry => {
      if (entry.intersectionRatio > 0) {
        entry.target.src = entry.target.dataset.src;
        observer.unobserve(entry.target);
      }
    });
  });
  imgList.forEach(img => {
    observer.observe(img);
  });
};

intersectionObserver 详情请看:
https://developer.mozilla.org/zh-CN/docs/Web/API/IntersectionObserver

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
js javascript
Projects
None yet
Development

No branches or pull requests

2 participants