jQuery懒加载(Lazy Loading)是一种优化网页性能的技术,它通过延迟加载页面中的图片或其他资源,直到用户滚动到它们的位置时才进行加载。这种技术可以显著减少页面初始加载时间,提高用户体验。
以下是一个简单的jQuery图片懒加载的实现示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Lazy Loading Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
img {
width: 100%;
height: auto;
display: block;
}
.lazy {
background-image: url('placeholder.jpg');
background-size: cover;
}
</style>
</head>
<body>
<img class="lazy" data-src="image1.jpg" alt="Image 1">
<img class="lazy" data-src="image2.jpg" alt="Image 2">
<img class="lazy" data-src="image3.jpg" alt="Image 3">
<!-- More images -->
<script>
$(document).ready(function() {
function lazyLoad() {
$('.lazy').each(function() {
if ($(this).offset().top < $(window).scrollTop() + $(window).height()) {
$(this).attr('src', $(this).data('src')).removeClass('lazy');
}
});
}
$(window).scroll(lazyLoad);
lazyLoad(); // Initial check
});
</script>
</body>
</html>
function throttle(func, wait) {
let timeout = null;
return function() {
const context = this;
const args = arguments;
if (!timeout) {
timeout = setTimeout(function() {
timeout = null;
func.apply(context, args);
}, wait);
}
};
}
$(window).scroll(throttle(lazyLoad, 200));
$('img').on('error', function() {
$(this).attr('src', 'default-placeholder.jpg');
});
通过以上方法,可以有效解决懒加载过程中遇到的一些常见问题,提升用户体验和页面性能。
领取专属 10元无门槛券
手把手带您无忧上云