Home > Article > Web Front-end > An example of lazy loading of images
When we browse large shopping websites such as Taobao and JD.com, many pictures often appear, and the pictures cost us a lot of traffic.
How do we solve this problem when writing web pages? At this time, we need to use the problem of lazy loading of our images, which not only solves the traffic problem, but also improves performance and so on.
Let’s take a look at the problem with lazy loading of images.
Title
*{
margin: 0;
padding: 0;
list-style-type: none;
}
html,body{
width: 100%;
height: 100%;
}
#p p{
width: 400px;
height: 500px;
/*border:1px solid #000;*/
display: inline-block;
margin:10px;
}
img{
width: 100%;
height: 100%;
}
// 获取距离父级距离
function getPos(obj) {
var t=0;//先声明两个变量 用来存储距离上面的高度 距离左边的高度
var l=0;
while (obj){//循环判断这个元素是否存在,存在才执行这个方法
t+=obj.offsetTop; // 加上距离父级的距离
l+=obj.offsetLeft;
obj=obj.offsetParent;// 有父级让他变成他的父级
}
return {left:l,top:t}; //把值传出去
}
window.onload=window.onscroll=function () {//滚动的时候和页面加载时执行的一样
var aImg=document.getElementsByTagName('img');//获取所有的元素img元素
var oSCrollT=document.body.scrollTop || document.documentElement.scrollTop;// 滚动条滚动高度
var oClh=document.documentElement.clientHeight;//可视区的高度
var oScr=oSCrollT + oClh; // 滚动条高度 + 可视区的高度
for(var i=0;i
if(oScr > getPos(aImg[i]).top){
aImg[i].src=aImg[i].getAttribute('_src'); //给src属性赋值
}
}
}
今天的内容就到这里,你学会了吗?
The above is the detailed content of An example of lazy loading of images. For more information, please follow other related articles on the PHP Chinese website!