web性能优化之js图片懒加载
2021-05-19 19:29
标签:isp ima idt inter display order box log attribute html css js 设置定时器延迟加载图片,优化网站打开时间,当图片出现在可见范围就加载图片,否则就不加载。 web性能优化之js图片懒加载 标签:isp ima idt inter display order box log attribute 原文地址:http://www.cnblogs.com/zt123123/p/7711381.html
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
li {
margin-top: 10px;
border-bottom: 1px solid #000;
list-style: none;
height: 100px;
}
.pic {
width: 200px;
padding: 10px;
height: 100px;
float: left;
background: url(img/timg.gif) no-repeat center center;
background-size: cover;
background-origin: content-box;
}
.pic img {
opacity: 0;
display: none;
border: 1px solid #000;
width: 100%;
height: 100%;
}
li:last-child {
margin-bottom: 10px;
}
.txt {
height: 100px;
line-height: 100px;
overflow: hidden;
}
var imgList = document.querySelectorAll("img");
var len = imgList.length;
function loadImg(curImg) {
var truesrc = curImg.getAttribute("trueimg");
var oImg = new Image();
var curPar = curImg.parentNode;
oImg.src = truesrc;
oImg.onload = function() {
curImg.src = this.src;
curImg.style.display = "block";
curPar.style.background = "none";
fadeIn(curImg);
oImg = null;
}
curImg.isLoaded = true;
}
function fadeIn(curImg) {
var tar = 1;
var interval = 10;
var duration = 500;
var step = (tar / duration) * interval;
var curOp = parseFloat(getComputedStyle(curImg, null)["opacity"]);
var timer = window.setInterval(function() {
if(curOp > 1) {
curImg.style.opacity = 1;
window.clearInterval(timer);
}
curOp += step;
curImg.style.opacity = curOp;
}, interval);
}
function handleImg() {
for(var i = 0; i ) {
var curImg = imgList[i];
if(curImg.isLoaded) {
continue;
}
var curPar = curImg.parentNode;
var a = curPar.clientHeight + curPar.offsetTop;
var b = document.documentElement.clientHeight + document.documentElement.scrollTop;
if(a b) {
loadImg(curImg);
}
}
}
setTimeout(handleImg, 1000);
window.onscroll = handleImg;