jQuery 图片延时加载(Lazy Loading)是一种优化网页性能的技术,它允许网页上的图片在用户滚动到它们的位置时才进行加载,而不是一次性加载所有图片。这样可以减少初始页面加载时间,提高用户体验。
以下是一个简单的 jQuery 图片延时加载的示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery Lazy Loading</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
img {
width: 100%;
height: auto;
display: block;
}
.lazy {
background: url('placeholder.jpg') no-repeat center center;
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()) {
var imgSrc = $(this).data('src');
$(this).attr('src', imgSrc).removeClass('lazy');
}
});
}
$(window).scroll(lazyLoad);
lazyLoad(); // Initial check
});
</script>
</body>
</html>
$(window).on('error', 'img', function() {
$(this).attr('src', 'default-error.jpg');
});
通过以上方法,可以有效实现 jQuery 图片延时加载,并解决一些常见问题。
没有搜到相关的沙龙