懒加载
"use strict";
var imgLazy = {
checkWebp : function() {
try {
return ( document.createElement('canvas').toDataURL('image/webp').indexOf('data:image/webp')==0 );
} catch(err) {
return false;
}
},
checkImgUrl : function(imgurl, imgObj) {
imgObj.src = imgurl;
imgObj.onerror = function() {
imgObj.src = imgurl.replace(/.webp$/, '.jpg');
imgObj.onerror = null;
};
},
getImgTop : function(img) {
var offsetTop = img.getBoundingClientRect().top,
winHeight = document.documentElement.clientHeight || document.body.clientHeight;
if (offsetTop < winHeight+2000) {
return true;
}
},
lazyLoadImg : function(imgsrc) {
var img = document.getElementsByTagName("img");
for (var i = 0, length = img.length; i < length; i++) {
if (img[i].getAttribute(imgsrc)) {
img[i].style.opacity = .5;
img[i].style.filter = "alpha(opacity = " + 50 + ")";
if ( this.getImgTop(img[i]) ) {
var url = img[i].getAttribute(imgsrc).replace(/.jpg$/, '.webp');
// 判断浏览器是否支持.webp格式
if( this.checkWebp() ) {
// 判断有没有.webp图片
this.checkImgUrl(url, img[i]);
} else {
img[i].src = img[i].getAttribute(imgsrc);
}
img[i].removeAttribute(imgsrc);
img[i].style.webkitTransition = 'opacity 1s';
img[i].style.opacity = 1;
img[i].style.filter = "alpha(opacity = " + 100 + ")";
}
}
}
},
throttle : function(method, parma,context) {
clearTimeout(method.tId);
method.tId = setTimeout(function(){
method.call(context, parma);
}, 200);
},
init : function() {
var oThis = this;
oThis.lazyLoadImg('data-src');
window.onscroll = function() {
oThis.throttle(oThis.lazyLoadImg, 'data-src', oThis);
};
}
};
imgLazy.init();

浙公网安备 33010602011771号