图片懒加载
- 监听页面的滚动事件,当滚动位置到图片的top位置时加载图片;
let imgs = document.querySelectorAll('img');
imgs = Array.prototype.slice.apply(imgs);
console.log(imgs)
window.addEventListener('scroll', function () {
let vh = window.innerHeight;
imgs.forEach(i => {
if (i.getBoundingClientRect().top < vh) {
let src = i.getAttribute('data-src');
i.setAttribute('src', src);
setTimeout(() => {
imgs.splice(i, 1);
}, 6000)
}
})
})
- 使用IntersectionObserver观察图片与可视区域的相交情况来加载图片;
function callback(entries, observer) {
entries.forEach(entry => {
if (entry.isIntersecting) {
let currentImg = entry.target;
let src = currentImg.getAttribute('data-src');
currentImg.setAttribute('src', src);
observer.unobserve(currentImg);
}
})
}
let observer = new IntersectionObserver(callback);
imgs.forEach(img => {
observer.observe(img);
})
MDN关于IntersectionObserver的描述
IntersectionObserver的浏览器兼容情况