图片预加载,即图片提前加载,可以保证图片快速、无缝的发布,用户需要查看时可直接从本地缓存中渲染,适用于图片占据很大比例的网站。

图片出现在视窗内的情况: offsetTop < clientHeight + scrollTop
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>图片预加载和懒加载</title>
<style>
body {
background: #f4f4f4;
}
.content {
width: 90%;
margin: 0 auto;
display: flex;
flex-wrap: wrap;
}
img {
background: #eeeeee;
width: 100%;
height: 200px;
}
.box {
width: 20%;
height: 350px;
background: white;
box-sizing: border-box;
border: 1px solid #f4f4f4;
padding: 20px 20px 0 20px;
}
.box:hover {
width: 20%;
height: 350px;
background: white;
box-sizing: border-box;
border: 1px solid #f4ea43;
}
.price {
font-size: 20px;
}
p {
font-size: 14px
}
</style>
</head>
<body>
<div class="content">
<div class="box">
<img style="width: 100%"
data-src="https://img.alicdn.com/tps/i2/TB1FA1kKXXXXXalXVXXgrdL_XXX-980-980.jpg_350x350q90.jpg_.webp">
<p>春季男鞋日常休闲鞋英伦风男士潮流休闲皮鞋低帮鞋男单鞋男豆豆鞋</p>
<div style="display: flex;justify-content: space-between">
<div style="color: #F40;font-size: 12px">¥<span class="price">29.9</span></div>
<div style="color: #9ca0aa;font-size: 12px">销量:1</div>
</div>
</div>
</div>
</body>
<script>
function throttle(fn, delay, interval) {
// 函数绑定在scroll事件上,当页面滚动时,避免函数高频触发
var timeout = null, startTime = new Date();
return function () {
var curtime = new Date();
clearTimeout(timeout);
if (curtime - startTime >= interval) {
fn();
startTime = curtime;
} else {
timeout = setTimeout(fn, delay);
}
}
}
function lazyload() {
var images = document.getElementsByTagName("img");
var n = 0;
return function () {
var seeHeight = document.documentElement.clientHeight;
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
for (var i = n; i < images.length; i++) {
if (images[i].offsetTop < seeHeight + scrollTop) {
if (!images[i].getAttribute("src")) {
images[i].src = images[i].getAttribute("data-src");
}
n = i + 1;
}
}
}
}
var loadImages = lazyload()
loadImages();
window.addEventListener("scroll", throttle(loadImages, 500, 1000), false);
</script>
</html>
网友评论