前端中实现图片懒加载,一次性加载所有资源容易造成网页性能变差,用户体验比较差,所以我们一般需要前端请求出来的数据进行处理,图片先显示可视区域的一部分,然后滚动部分按需加载。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
* {
margin: 0;
padding: 0;
list-style: none;
box-sizing: border-box;
}
h1 {
text-align: center;
}
.box {
width: 100%;
}
.box ul {
width: 100%;
display: flex;
justify-content: space-between;
flex-wrap: wrap;
}
.box ul li {
width: 50%;
text-align: center;
}
.box ul li img {
display: block;
margin: 0 auto 20px;
width: 180px;
height: 300px;
}
.box ul li p {
font-size: 16px;
padding-bottom: 20px;
}
</style>
<body>
<div class="box">
<h1>图片懒加载</h1>
<ul>
</ul>
</div>
</body>
</html>
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<!-- 图片懒加载 -->
<script src="https://cdn.bootcdn.net/ajax/libs/jquery_lazyload/1.9.7/jquery.lazyload.js"></script>
<script>
$.ajax({
url: 'https://api.it120.cc/small4/shop/goods/list',
type: 'get',
dataType: 'json',
success: function (res) {
console.log(res.data);
$.each(res.data, function (index, item) {
$('.box ul').append(`<li><img data-original="${item.pic}" src="./loading.gif" alt="">
<p>${item.name}</p></li>`)
//我们来说明几点:
//1.data-original="" 这个属性是规定好的必须要用original定义不能随便写哈,不然不起作用;
//2.data-original="这里写真实路径" 而src="这里可以写一个loading图片,也可以不写"
})
$('.box ul li img').lazyload(); //这个lazyload()方法很重要别忘了加
},
error: function (err) {
console.log(err)
}
})
</script>
网友评论