js如何实现懒加载
实现懒加载的方法
使用Intersection Observer API
Intersection Observer API是现代浏览器提供的高效方法,用于监听元素是否进入视口。
const lazyImages = document.querySelectorAll('img[data-src]');
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
observer.unobserve(img);
}
});
});
lazyImages.forEach(img => observer.observe(img));
HTML中需要将真实URL放在data-src属性:
<img data-src="real-image.jpg" alt="Lazy loaded image">
传统滚动事件监听
对于不支持Intersection Observer的旧浏览器,可以使用滚动事件实现。
function lazyLoad() {
const lazyImages = [].slice.call(document.querySelectorAll('img.lazy'));
if (lazyImages.length === 0) {
window.removeEventListener('scroll', lazyLoad);
return;
}
lazyImages.forEach(img => {
if (img.getBoundingClientRect().top <= window.innerHeight + 100) {
img.src = img.dataset.src;
img.classList.remove('lazy');
}
});
}
window.addEventListener('scroll', lazyLoad);
document.addEventListener('DOMContentLoaded', lazyLoad);
动态加载组件
对于Vue等现代框架,可以使用动态导入实现组件懒加载。
const LazyComponent = () => import('./LazyComponent.vue');
在React中可以使用React.lazy:
const LazyComponent = React.lazy(() => import('./LazyComponent'));
图片预加载优化
为了提升用户体验,可以添加加载状态和错误处理。
const img = new Image();
img.src = 'image-to-preload.jpg';
img.onload = () => {
// 图片加载完成后的处理
};
img.onerror = () => {
// 加载失败的处理
};
注意事项
- 合理设置阈值,避免过早或过晚加载
- 对于重要内容避免懒加载,以免影响SEO
- 移动端需要考虑网络状况,可以适当提前加载
- 使用loading="lazy"作为渐进增强方案:
<img src="image.jpg" loading="lazy" alt="...">







