imglazyload图片延迟加载(jQuery)
2011-06-20 下午 - JS/Ajax/AS - JQuery - 插件
这个小效果还是3个月前写的,太忙,一直没空更新blog,刚好有点空闲,抽出来简单弄弄了~
container容器,attr属性,timeout延时。这些都可以有自己灵活控制的!原理简单不过了,图片先不设置src属性,浏览器就不会产生请求,监听起滚动条和窗口大小的事件,通过判断图片是否处于当前可视区域(offset的left和top方向分别小于scrollTop+clientHeight和scrollLeft+clientWidth)来控制图片是否显示,显示则设置img对象的src属性为标签中自定义属性的值!
主要代码
this.imgNum = this.container.find('img['+ this.options.attr +']');
var _this = this;
if(this.imgNum.length){
this.timer&&clearTimeout(this.timer);
this.timer = setTimeout(function(){
var arr = [],gc = _this.getClient();
$.each(_this.imgNum,function(i,o){
if($(o).offset().top <= gc.top && $(o).offset().left <= gc.left){
var attrval = $(o).attr('lazysrc');attrval&&$(o).attr('src',attrval).removeAttr('lazysrc').hide().fadeIn();
}else{
arr.push(o);
}
});
_this.imgNum = arr;
},this.options.timeout);
}else{
$(window).unbind('scroll',this.check);
$(window).unbind('resize',this.check);
}