在网站开发中,如何实现图片的懒加载?
- 在可视化区域加载图片(解决如何判断图片已经在可视化区域)
- 图片的加载
<div class="image">
<img src="" alt="" data-src="https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=3932093531,259615635&fm=26&gp=0.jpg" />
</div>
第一种方案监听浏览器的 scroll 事件,通过调用getBoundingClientRect
函数返回的值判断图片是否进入可视化区域。
(function() {
window.addEventListener(
'scroll',
debounce(() => {
const images = document.querySelectorAll('img[data-src]');
images.forEach((image) => {
const top = image.getBoundingClientRect().top;
if (top < document.documentElement.clientHeight && !image.getAttribute('src')) {
const src = image.getAttribute('data-src');
image.removeAttribute('data-src');
image.setAttribute('src', src);
}
});
}, 500)
);
const debounce = (fn, wait) => {
let timer = null;
return () => {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
fn.apply(this);
}, wait);
};
};
})();
第二种方案使用IntersectionObserver
接口,当一个 IntersectionObserver 对象被创建时,其被配置为监听根中一段给定比例的可见区域。
(function() {
const observer = new IntersectionObserver((changes) => {
// changes: 目标元素集合
changes.forEach((change) => {
if (change.isIntersecting) {
const img = change.target;
img.src = img.dataset.src;
observer.unobserve(img);
}
});
});
const images = document.querySelectorAll('img[data-src]');
images.forEach((image) => {
observer.observe(image);
});
})();
以上就是【js实现图片的懒加载】的全部内容了,欢迎留言评论进行交流!