网页图片过多导致加载缓慢,这个时候可以使用懒加载的方式,利用img标签在src为空时不会加载资源的特性,当图片在浏览器窗口内显示时,再加载。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.container{
display: flex;
justify-content: space-between;
width: 600px;
margin: 0 auto;
flex-wrap: wrap;
}
.container img{
width: 49%;
height: 100%;
margin-bottom: 10px;
}
img[src=""]{
background-color: pink;
}
</style>
</head>
<body>
<div class="container">
<!-- <img src="" alt="1" data-src="test.jpg">-->
</div>
<script>
//通过script标签同步加载特效批量添加内容
let container = document.querySelector(".container");
let img = `<img src="" alt="1" data-src="https://www.mrdiv.top/static/img/p2.f4999c4.jpg">`;
for (let i = 0;i<60;i++){
container.insertAdjacentHTML("beforeEnd",img)
}
</script>
<script>
window.onload = function () {
lazyLoad();
};
document.onscroll = throtte(function () {
lazyLoad();
});
function lazyLoad() {
let imgs = document.body.querySelectorAll("img");
let wHeight = window.innerHeight;
let sHeight = document.documentElement.scrollTop;
imgs.forEach(item=>{
//判断图片是否在视窗内
if(item.offsetTop<wHeight+sHeight){
item.src = item.getAttribute("data-src")
}
})
}
//节流函数,防止触发过渡频繁
function throtte(func,delay = 300) {
let timer = null;
return function () {
let args = arguments;
if(!timer){
func.apply(this,args);
timer = setTimeout(()=>{
timer = null;
},delay)
}
}
}
</script>
</body>
</html>