jquery懒加载
jQuery懒加载的实现方法
懒加载(Lazy Load)是一种优化网页性能的技术,通过延迟加载非关键资源(如图片)来减少初始页面加载时间。以下是使用jQuery实现懒加载的几种方法:
使用jQuery Lazy插件
jQuery Lazy是一个轻量级插件,专门用于实现懒加载功能。
安装插件:
<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: 0
});
HTML标记:
<img class="lazy" data-src="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 >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);
}
使用Intersection Observer API
现代浏览器支持Intersection Observer API,性能比滚动事件监听更好:
if ("IntersectionObserver" in window) {
const lazyImages = $("img[data-src]");
const imageObserver = new IntersectionObserver(function(entries) {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
imageObserver.unobserve(img);
}
});
});
lazyImages.each(function() {
imageObserver.observe(this);
});
}
注意事项
- 确保为懒加载图片设置占位尺寸,避免布局跳动
- 考虑添加加载中的占位图或旋转动画
- 移动端需要特别处理触摸事件
- 对于SEO,可以考虑使用noscript标签提供后备方案
以上方法可以根据项目需求选择使用,插件方案更全面但会增加文件大小,自定义方案更灵活但需要更多调试。







