详情案例可参看本网站改造后的效果,目前覆盖首页、栏目页、内容页界面。
核心JS代码:
<scripttype="text/javascript">
varfgm={
on:function(element,type,handler){
returnelement.addEventListener?element.addEventListener(type,handler,false):element.attachEvent("on"+type,handler)
},
bind:function(object,handler){
returnfunction(){
returnhandler.apply(object,arguments)
}
},
pageX:function(element){
returnelement.offsetLeft+(element.offsetParent?arguments.callee(element.offsetParent):0)
},
pageY:function(element){
returnelement.offsetTop+(element.offsetParent?arguments.callee(element.offsetParent):0)
},
hasClass:function(element,className){
returnnewRegExp("(^|\s)"+className+"(\s|$)").test(element.className)
},
attr:function(element,attr,value){
if(arguments.length==2){
returnelement.attributes[attr]?element.attributes[attr].nodeValue:undefined
}
elseif(arguments.length==3){
element.setAttribute(attr,value)
}
}
};
//延时加载
functionLazyLoad(obj){
this.lazy=typeofobj==="string"?document.getElementById(obj):obj;
this.aImg=this.lazy.getElementsByTagName("img");
this.fnLoad=fgm.bind(this,this.load);
this.load();
fgm.on(window,"scroll",this.fnLoad);
fgm.on(window,"resize",this.fnLoad);
}
LazyLoad.prototype={
load:function(){
variScrollTop=document.documentElement.scrollTop||document.body.scrollTop;
variClientHeight=document.documentElement.clientHeight+iScrollTop;
vari=0;
varaParent=[];
varoParent=null;
variTop=0;
variBottom=0;
varaNotLoaded=this.loaded(0);
if(this.loaded(1).length!=this.aImg.length){
for(i=0;i<aNotLoaded.length;i++){
oParent=aNotLoaded[i].parentElement||aNotLoaded[i].parentNode;
iTop=fgm.pageY(oParent);
iBottom=iTop+oParent.offsetHeight;
if((iTop>iScrollTop&&iTop<iClientHeight)||(iBottom>iScrollTop&&iBottom<iClientHeight)){
aNotLoaded[i].src=fgm.attr(aNotLoaded[i],"data-img")||aNotLoaded[i].src;
aNotLoaded[i].className="loaded";
}
}
}
},
loaded:function(status){
vararray=[];
vari=0;
for(i=0;i<this.aImg.length;i++)
eval("fgm.hasClass(this.aImg[i],"loaded")"+(!!status?"&&":"||")+"array.push(this.aImg[i])");
returnarray
}
};
//应用添加
fgm.on(window,"load",function(){newLazyLoad("box")});
fgm.on(window,"load",function(){newLazyLoad("bxslider")});
</script>在添加JS后直接在应用添加里面添加对应需要执行懒加载的区域即可,图片的代码调整为<img data-img="XXX"/>
内容页需要执行懒加载的话,参考:《dede手机站调用PC站图片》中函数的使用方法即可。需要帮助调整的,可在百家号贤话师兄处关注留言。