html代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<style>
.dis_none{
display : none;
}
</style>
<body>
<section class='page1'>
<img src="" data-src='./img.png'>
<img src="" data-src='./img.png'>
<img src="" data-src='./img.png'>
</section>
<section class='page2 dis_none'>
<img src="" data-src='./img.png'>
<img src="" data-src='./img.png'>
<img src="" data-src='./img.png'>
</section>
</body>

javascript 代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
var lazyLoad=function(obj,fun){
var load = function (obj){
var loadThis=this;
this.imgArr=[];
this.num=0;
$(obj+" img").each(function(){
if($(this).attr("data-src")){
loadThis.imgArr[loadThis.imgArr.length]=$(this).attr("data-src");
$(this).attr("src",loadThis.imgArr[loadThis.imgArr.length-1]);
$(this).attr("data-src","");
}
});
if(typeof fun=="function"){
this.callBack(fun)
}
};
load.prototype.callBack=function(fun){
var loadThis=this,len = loadThis.imgArr.length-1;
for(var i=0; i<this.imgArr.length;i++){
var img = new Image();
img.src = this.imgArr[i];
img.onload=function(){
if(loadThis.num<len){
loadThis.num++;
}else {
fun()
}
}
img.onerror=function(){
if(loadThis.num<len){
loadThis.num++;
}else {
fun()
}
}
}
};
return new load(obj,fun)
};

ex:

1
2
3
4
5
6
lazyLoad('.page1', function(){
lazyLoad('.page2', function(){
$('.page1').addClass('dis_none');
$('.page2').removeClass('dis_none');
});
});

目前版本 依赖zepto库。迟点更新无依赖版本。