图片懒加载(Lazy Load)是一种优化网页性能的技术,它可以延迟图片的加载时间,只有当用户滚动到该图片的位置时才会进行加载。这样可以减少页面的初始加载时间,提高页面的响应速度和用户体验。
以下是使用浏览器原生支持的 IntersectionObserver
接口,监测元素与视口交叉,当图片进入视口时触发图片的加载。
html代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="./index2.css">
</head>
<body>
<div>
<h1>图片相册</h1>
<img data-src="http://pic1.win4000.com/wallpaper/2018-09-19/5ba21a3006800.jpg" alt="">
<img data-src="https://t7.baidu.com/it/u=1785207335,3397162108&fm=193&f=GIF" alt="">
<img data-src="https://t7.baidu.com/it/u=338595665,4065109605&fm=193&f=GIF" alt="">
<img data-src="https://t7.baidu.com/it/u=1732966997,2981886582&fm=193&f=GIF" alt="">
<img data-src="https://t7.baidu.com/it/u=2581522032,2615939966&fm=193&f=GIF" alt="">
<img data-src="https://t7.baidu.com/it/u=245883932,1750720125&fm=193&f=GIF" alt="">
<img data-src="https://t7.baidu.com/it/u=3423293041,3900166648&fm=193&f=GIF" alt="">
<img data-src="https://t7.baidu.com/it/u=3241434606,2550606435&fm=193&f=GIF" alt="">
<img data-src="https://t7.baidu.com/it/u=1417505637,1247476664&fm=193&f=GIF" alt="">
<img data-src="https://img0.baidu.com/it/u=775184654,1087701200&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500">
<img data-src="https://lmg.jj20.com/up/allimg/1114/1110200ZS0/2011100ZS0-9-1200.jpg" alt="">
</div>
</body>
<script src="./index2.js"></script>
</html>
css代码:
img{
width: 100vw;
transform: translateX(50%);
opacity: 0;
transition: all 500ms;
}
.fade{
transform: translateX(0);
opacity: 1;
transition: all 500ms;
}
js代码:
const targets = document.querySelectorAll('img');
const lazyload = target =>{
const io = new IntersectionObserver((entries,observer) =>{
entries.forEach((entry)=>{
console.log("load img")
if(entry.isIntersecting){
const img = entry.target
const src = img.getAttribute("data-src")
img.setAttribute("src",src);
img.classList.add("fade")
observer.disconnect();
}
})
})
io.observe(target)
}
targets.forEach(lazyload);