1、懒加载。
<!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>
<body>
<div>
<ul>
<li>
<img data_src="./sex1.jpg" src="./sex1.jpg" alt="">
</li>
<li>
<img data_src="./sex2.jpg" src="./sex1.jpg" alt="">
</li>
<li>
<img data_src="./sex3.jpg" src="./sex1.jpg" alt="">
</li>
<li>
<img data_src="./sex4.jpg" src="./sex1.jpg" alt="">
</li>
<li>
<img data_src="./sex5.jpg" src="./sex1.jpg" alt="">
</li>
</ul>
</div>
</body>
<script>
//获取所有的img标签
let imgs = document.querySelectorAll("img")
// fn(imgs)
function fn(imgs){
// 遍历所有的img标签,获取dom
for(let i=0;i<imgs.length;i++){
//获取每张图片距离顶部的距离
let imgOffsetTop = imgs[i].offsetTop
// 获取每张图片被卷去的距离
let imgScrollTop = imgs[i].scrollTop
// 获取浏览器可视区高度
var interHeight = window.innerHeight
// 元素举例顶部的距离(offsetTop)-页面被卷去的高度(scrollTop)<=浏览器可视区的高度
if(imgOffsetTop-imgScrollTop<=interHeight){
// 将真正的src图片路径赋值给src属性
imgs[i].src=imgs[i].getAttribute("data_src")
console.log(imgs[4].getAttribute("data_src"))
}
}
}
window.addEventListener("scroll",()=>{
fn(imgs)
})
</script>
<style>
ul li {
width:200px;
height:200px;
list-style:none;
}
img {
width:200px;
/* height:200px; */
}
</style>
</html>
2、预加载。
<!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>
<body>
<div>
<ul>
<li>
<img src="./sex1.jpg" alt="" onclick="preLoad(urlList)">
</li>
</ul>
</div>
</body>
<script>
// 预加载图片路径
let urlList = ["./sex1.jpg","./sex2.jpg","./sex3.jpg","./sex4.jpg","./sex5.jpg"]
let num = 1
function preLoad(){
let imgs = document.querySelector("img")
imgs.src= urlList[num]
let img = new Image()
if(num<urlList.length-1){
img.src = urlList[num+1]
// onload是图片加载完成事件
img.onload = function(){
num++
console.log('图片预加载成功',num);
}
}
}
</script>
<style>
ul li {
width:200px;
height:200px;
list-style:none;
}
img {
width:200px;
}
</style>
</html>
效果图: