//定义预加载图片列表的函数(有参数)
jQuery.preloadImages = function(){
//遍历图片
for(var i = 0; i<arguments.length; i++){
jQuery("<img>").attr("src", arguments[i]);
}
}
// 你可以这样使用预加载函数
$.preloadImages("images/logo.png", "images/logo-face.png", "images/mission.png");
<img id="preload" src="http://media.opera.com/media/images/logo/Opera-logo-JPG.jpg" alt="preload" />
<script language="JavaScript">
//http://www.qiqiboy.com/2011/05/20/javascript-image-preload.html
var imageReady=(function(){
var list=[],
timer=null,
tick=function(){
for(var i=0;i<list.length;i++){
list[i].end?list.splice(i--,1):check.call(list[i],null);
}
list.length && (timer=setTimeout(tick,50)) || (timer=null);
},
/** overflow: 检测图片尺寸的改变
* img.__width,img.__height: 初载入时的尺寸
*/
check=function(){
if(this.width!==this.__width || this.height!==this.__height || this.width*this.height>1024){
this.onready.call(this,null);
this.end=true;
}
};
return function(img, onready, onload, onerror){
onready=onready || new Function();
onload=onload || new Function();
onerror=onerror || new Function();
if(typeof img == 'string'){
var src=img,
img=new Image();
img.src=src;
}
if(img.complete){
onready.call(img,null);
onload.call(img,null);
return true;
}
img.__width=img.width;
img.__height=img.height;
img.onready=onready;
check.call(img,null);
img.onload=img.onreadystatechange=function(){
if(img&&img.readyState&&img.readyState!='loaded'&&img.readyState!='complete'){return;}
onload.call(img,null);
img=img.onload=img.onerror=img.onreadystatechange=null;
}
img.onerror=function(){
onerror.call(img,null);
img.end=true;
img=img.onload=img.onerror=img.onreadystatechange=null;
}
if(!img.end){
list.push(img);
if(timer===null) timer=setTimeout(tick,50);
}
}
})();
/* 使用方式
* 以此图片节点为例:<img id="preload" src="http://wwww.qiqiboy.com/preload.jpg" alt="preload" />
*/
imageReady(document.getElementById('preload'),function(){
console.log('onready');
},function(){
console.log('onload');
},function(){
console.log('onerror');
});
/* 在调用函数中使用图片尺寸, 调用函数中的this指向preload图片对象 */
//imageReady(document.getElementById('preload'),function(){
// console.log('preload image width: '+this.width+'px, height: '+this.height+'px');
//})
/* 也可以直接使用url */
//imageReady('http://wwww.qiqiboy.com/preload.jpg',function(){
//console.log('preload image width: '+this.width+'px, height: '+this.height+'px');
//})
</script>