JQuery 图片延迟加载
发表:2016-07-07 19:23
作者:loeyae@gmail.com
$.extend({'lazyload':function(options){
this.defaults = {
loadimg:'',
defaultimg:'',
width:$(window).width(),
height:$(window).height()
}
this.options = $.extend(this.defaults,options);
this.load = function(t,l){
var top = parseInt(this.options.height)+parseInt(t);
var left = parseInt(this.options.width)+parseInt(l);
var $this = this;
var load = this.options.load;
$('img').each(function(i){
var img = $(this);
var offset = img.offset();
if(offset.left > left || offset.top > top)
return false;
var lazysrc = img.attr('lazysrc');
var _src = img.attr('src');
if(img.attr('src') != lazysrc && lazysrc && !img.data('img')){
if(load) {
if(img.attr('src')!=$this.options.loadimg)
img.attr('src',$this.options.loadimg);
}
var image = new Image();
image.src = lazysrc;
img.data('img',image);
image.onload = function(){
img.attr('src',lazysrc);
}
image.onerror = function(){
img.attr('src',_src);
}
}
});
}
this.liveevent = function(){
var $this = this;
this.load(0,0);
if (this.options.loadimg){
var limg = new Image();
limg.src = this.options.loadimg;
limg.onload = function (){
$this.options.load = true;
}
}
$(window).scroll(function(){
var top = $(this).scrollTop();
var left = $(this).scrollLeft();
$this.load(top, left);
});
}
this.liveevent();
}})
$.lazyload({loadimg:'images/2.gif'});