jQuery延迟加载图片(Lazy Loading)是一种优化网页性能的技术,它只在图片即将进入用户视口时才加载图片。这样可以减少初始页面加载时间,提高用户体验,特别是在包含大量图片的网页上。
以下是一个使用jQuery实现图片延迟加载的示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Lazy Loading Images</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
img {
width: 100%;
height: auto;
display: block;
margin-bottom: 20px;
}
</style>
</head>
<body>
<img data-src="image1.jpg" alt="Image 1">
<img data-src="image2.jpg" alt="Image 2">
<img data-src="image3.jpg" alt="Image 3">
<!-- 更多图片 -->
<script>
$(document).ready(function() {
function lazyLoadImages() {
$('img[data-src]').each(function() {
if ($(this).offset().top < $(window).scrollTop() + $(window).height()) {
var src = $(this).attr('data-src');
$(this).attr('src', src).removeAttr('data-src');
}
});
}
$(window).scroll(function() {
lazyLoadImages();
});
// 初始加载视口内的图片
lazyLoadImages();
});
</script>
</body>
</html>
$('img').on('error', function() {
$(this).attr('src', 'placeholder.jpg');
});
通过以上方法,可以有效实现图片的延迟加载,并解决常见的技术问题。
领取专属 10元无门槛券
手把手带您无忧上云