图片延迟加载
在做一个图片较多的网站中,如果一次性加载全部图片难免网站打开速度有点慢,所以 嘿 ~ 嘿 ~ 嘿~
<script type="text/javascript">
(function($){
var queue = [];var queueMap = [];var coordinate = {};var n = 0;lazyLoder = {
push:push,
load:load,
clear:clear,
show:show
}
function show(){
alert(queueMap);
alert(queueMap.length);
alert(queue.length);
}
function push(img){
$(img).attr("sid")?$(img).attr("sid"):$(img).attr("sid",n++);
var id = $(img).attr("sid");
if(!queueMap[id]){
queue.push(img);
queueMap[id] = id;
}
}
function load(){
if(queue.length==0){return}
computeCoodinate();
var temp = [];
for (var i = 0; i < queue.length ;i++ ){
if($(queue[i]).attr("isOK")==1){
temp.push(i);
continue;
}
if(check(queue[i])==true){
loadIMG(queue[i]);
temp.push(i);
$(queue[i]).attr("isOK",1);
}
}
while(temp.length>0){
queue.splice(temp.pop(),1);
}
}
function clear(){
queue.length=0;
}
/*private function*/
function computeCoodinate(){
var windowHeight = $(window).height();
var windowWidth = $(window).width();
var scrollTop = document.body.scrollTop||document.documentElement.scrollTop;
coordinate.down = scrollTop > (coordinate.top?coordinate.top:0);
coordinate.up = scrollTop < (coordinate.top?coordinate.top:0);
coordinate.top = scrollTop;
coordinate.bottom = scrollTop + windowHeight;
}
function check(target){
var offset = $(target).offset();
var height = $(target).height();
var flag = true;
flag = flag && (offset.top>coordinate.top);
flag = flag && (offset.top < coordinate.bottom);
if (flag == false){
flag = flag && ((offset.top+height) > coordinate.top);
flag = flag && ((offset.top+height) < coordinate.bottom);
}
return flag;
}
function loadIMG(img){
setTimeout(function(){
$(img).attr("src",$(img).attr("lazy"));
},1);
}
})($)
var lazyloadImgID = setInterval(function(){
$("img[lazy]").each(function(){
lazyLoder.push(this)
});
lazyLoder.load();
},1);
$(document).ready(function(){
clearInterval(lazyloadImgID);
$("img[lazy]").each(function(){
lazyLoder.push(this);
});
lazyLoder.load();
$(window).bind("scroll",lazyLoder.load).bind("resize",lazyLoder.load);
});
</script>