网页图片懒加载(LazyLoad)是提升页面性能的关键技术,通过延迟加载非可视区域图片,可有效减少首屏资源加载量。本文将通过两种典型实现方案解析其核心原理。
实现原理: 通过现代浏览器提供的 Intersection Observer API 观察图片元素与视口的交叉状态,智能判断加载时机。
实现步骤:
修改图片标签属性
<img class="lazyload"
data-src="real-image.jpg"
src="placeholder.jpg">
创建观察器实例
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
observer.unobserve(img); // 停止已加载图片的观察
}
});
}, {
rootMargin: '0px 0px 200px 0px' // 预加载200px区域
});
绑定观察目标
document.querySelectorAll('.lazyload').forEach(img => {
observer.observe(img);
});
优势特性:
实现原理: 通过监听滚动事件,手动计算图片位置判断是否进入可视区域。
核心实现:
function lazyLoad() {
const images = document.querySelectorAll('.lazyload');
const viewHeight = window.innerHeight;
images.forEach(img => {
const rect = img.getBoundingClientRect();
if (rect.top < viewHeight + 100) { // 预加载100px
img.src = img.dataset.src;
img.classList.remove('lazyload');
}
});
}
// 添加防抖优化
const debounceLoad = _.debounce(lazyLoad, 200);
window.addEventListener('scroll', debounceLoad);
window.addEventListener('resize', debounceLoad);
lazyLoad(); // 初始化加载
优化要点:
响应式适配
<img data-srcset="small.jpg 480w, medium.jpg 800w"
data-sizes="(max-width: 600px) 480px, 800px">
加载状态管理
.lazyload {
opacity: 0;
transition: opacity 0.3s;
}
.lazyloaded {
opacity: 1;
}
错误处理
img.onerror = function() {
this.src = 'fallback.jpg';
this.removeAttribute('data-src');
}
SEO友好方案
<noscript>
<img src="real-image.jpg">
</noscript>
特性 | Intersection Observer | 滚动监听 |
---|---|---|
性能表现 | 优秀(原生API) | 依赖优化程度 |
代码复杂度 | 简单 | 中等 |
浏览器兼容 | IE部分不支持 | 全兼容 |
预加载能力 | 支持rootMargin配置 | 需手动计算 |
交叉比例检测 | 支持threshold配置 | 需自行实现 |
选型建议:
通过合理运用懒加载技术,可使页面加载性能提升40%-60%。建议结合CDN、图片压缩等方案形成完整的性能优化体系。