jquery 懒加载
jQuery 懒加载的实现方法
懒加载(Lazy Load)是一种优化网页性能的技术,延迟加载非关键资源(如图片),直到用户滚动到它们附近时才加载。以下是几种常见的实现方法:
使用 jQuery Lazy 插件
jQuery Lazy 是一个轻量级的懒加载插件,支持图片、iframe 和其他内容。
安装插件:
<script src="https://cdn.jsdelivr.net/npm/jquery-lazy@1.7.11/jquery.lazy.min.js"></script>
基本用法:

$("img.lazy").lazy({
effect: "fadeIn",
effectTime: 1000,
threshold: 200 // 提前 200px 加载
});
HTML 结构:
<img class="lazy" data-src="path/to/image.jpg" alt="Lazy Loaded Image">
自定义 jQuery 懒加载
如果不想依赖插件,可以通过监听滚动事件实现懒加载。
核心代码:

$(window).on("scroll", function() {
$("img[data-src]").each(function() {
if (isElementInViewport(this)) {
$(this).attr("src", $(this).data("src")).removeAttr("data-src");
}
});
});
function isElementInViewport(el) {
var rect = el.getBoundingClientRect();
return (
rect.top <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.bottom >= 0
);
}
HTML 结构:
<img data-src="path/to/image.jpg" alt="Lazy Loaded Image">
使用 Intersection Observer API
现代浏览器支持 Intersection Observer API,性能更好。
代码示例:
if ("IntersectionObserver" in window) {
const observer = new IntersectionObserver(function(entries) {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
observer.unobserve(img);
}
});
});
$("img[data-src]").each(function() {
observer.observe(this);
});
}
注意事项
- 为懒加载图片设置占位高度,避免页面抖动。
- 兼容性考虑:Intersection Observer 不支持旧浏览器,需回退到滚动事件方案。
- SEO 优化:搜索引擎可能不执行 JavaScript,建议结合
<noscript>标签。
<noscript>
<img src="path/to/image.jpg" alt="Fallback Image">
</noscript>
通过以上方法,可以有效实现图片懒加载,提升页面加载速度和用户体验。





