用多了懒加载插件,尝试一下自己撸一个,顺便了解其中原理和实现方法吧。
什么是懒加载
懒加载其实就是延迟加载,是一种对网页性能优化的方式,比如当访问一个页面的时候,优先显示可视区域的图片而不一次性加载所有图片,当需要显示的时候再发送图片请求,避免打开网页时加载过多资源。
什么时候用懒加载
当页面中需要一次性载入很多图片的时候,往往都是需要用懒加载的。
懒加载原理
我们都知道HTML中的<img>标签是代表文档中的一个图像。。说了个废话。。
<img>标签有一个属性是src,用来表示图像的URL,当这个属性的值不为空时,浏览器就会根据这个值发送请求。如果没有src属性,就不会发送请求。
嗯?貌似这点可以利用一下?
我先不设置src,需要的时候再设置?
nice,就是这样。
我们先不给<img>设置src,把图片真正的URL放在另一个属性data-src中,在需要的时候也就是图片进入可视区域的之前,将URL取出放到src中。
实现
HTML结构
<div id="showBox">
</div>
<div id="scrollBox">
<div class="scrollBox-item">
</div>
</div>
css
<style type="text/css">
html {
font-size: calc(100vw/700);
}
#showBox {
background-color: green;
color: #ffffff;
text-align: center;
padding: 10rem;
font-size: 25rem;
}
#scrollBox {
height: 400rem;
overflow-y: scroll;
border: 2rem solid #008000;
margin-top: 100rem;
padding: 10rem;
}
.scrollBox-item {
height: 1000rem;
display: flex;
flex-direction: column;
align-items: center;
}
.box {
display: flex;
justify-content: center;
align-items: center;
background-color: #008000;
color: #ffffff;
padding: 10rem;
}
.box img {
width: 300rem;
height: 300rem;
}
.box1 {
background-color: red;
}
.box2 {
background-color: blueviolet;
}
.box3 {
background-color: #000000;
}
.box4 {
background-color: cadetblue;
}
</style>
js代码
<script type="text/javascript">
var img;
const scrollBox = document.getElementsByClassName('scrollBox-item')[0];
const showBox = document.getElementById('showBox');
const boxArr = document.getElementsByClassName('box');
// 设置图片真实地址
function toggle(index, type) {
if (type == 'show') {
showBox.innerHTML = `第${index+1}个出现`;
boxArr[index].children[0].src = img;
} else {
showBox.innerHTML = `第${index+1}个消失`;
boxArr[index].children[0].src = '';
}
showBox.style.backgroundColor = window.getComputedStyle(boxArr[index]).getPropertyValue("background-color");
};
// 监听器
function observe(el) {
Array.prototype.slice.call(el).map((item, index) => {
let io = new IntersectionObserver((res) => {
if (res[0].intersectionRect.top <= 0) {
toggle(index, 'hide');
} else {
toggle(index, 'show');
}
});
io.observe(item)
})
}
// 加载图片
function setImg() {
let html = '';
for (let i = 1; i < 100; i++) {
html += `<div class="box box${i}">
<img alt="加载中..." data-src="https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=3663359702,1992818410&fm=26&gp=0.jpg" >
</div>`
}
scrollBox.innerHTML = html;
img = document.getElementsByClassName('box')[0].children[0].getAttribute('data-src');
observe(boxArr)
}
setImg()
</script>
网友评论