图片的预加载(待续)
1.预加载的好处
提高打开页面的速度,提高用户的体验。
2.缺点
增加了无用的请求。
3.实现
function preLoad(url,fn){ var img = new Image();
img.src = url;
if(img.complete){
fn.call(img);
}else{
img.onload = function(){
img.onload = null;
fn.call(img);
}
} }
提高效率获取图片尺寸:参考
var imgReady = (function(){ var list = [],intervalId = null, tick = function(){
for(var i=0;i<list.length;i++){
list[i].end?list.splice(i--,1):list[i]();
}
!list.length&&stop();
},
stop = function(){
clearInterval(intervalId);
intervalId = null;
};
return function(url,ready,load,error){
var onready,width,height,newWidth,newHeight,img = new Image();
img.src = url;
if(img.complete){
ready.call(img);
load&&load.call(img);
return;
}
width = img.width;
height = img.height;
img.onerror = function(){
error&&error.call(img);
onready.end = true;
img = img.onload = img.onerror = null;
}
onready = function(){
newWidth = img.width;
newHeight = img.height;
if(newWidth !== width || newHeight !== height||newWIdth*newHeight >1024){
ready.call(img);
onready.end = true;
}
}
onready();
img.onload = function(){
!onready.end && onready();
load && load.call(img);
img = img.onload = img.onerror = null;
}
if(!onready.end){
list.push(onready);
if(intervalId === null){
intervalId = setInterval(tick,40);
}
}
}
})()
参考文献:
http://www.cnblogs.com/rt0d/archive/2011/04/17/2018646.html
http://www.cssbox.net/js-img-onload.html