-
Notifications
You must be signed in to change notification settings - Fork 22
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
Labels
js
javascript
Comments
图片懒加载其实就是用一个自定义属性存储图片的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 详情请看: |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
图片懒加载原理及如何实现
The text was updated successfully, but these errors were encountered: