图片预加载技术(存在问题,已修复)
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>无标题文档</title> <script type="text/javascript"> var newload= function(){ urlone="http://www.leyoo.com/Public/nImg/Zhuanti/20131231/run_img_" urllast=".png" for(var i=1; i<9; i++) { url = urlone + i + urllast; oid = "im"+i; imgLoad(url,fimg); } } var fimg=function(x,y){ document.getElementById(oid).width = x; document.getElementById(oid).height = y; document.getElementById(oid).src = url; } var imgLoad = function (url, callback) { var img = new Image(); img.src = url; if (img.complete) { callback(img.width, img.height); } else { img.onload = function () { callback(img.width, img.height); img.onload = null; }; }; }; </script> </head> <body> <a onClick="newload()">点击</a> <img src="myFocus_white.gif" id="im1" /> <img src="myFocus_white.gif" id="im2"/> <img src="myFocus_white.gif" id="im3"/> <img src="myFocus_white.gif" id="im4"/> <img src="myFocus_white.gif" id="im5"/> <img src="myFocus_white.gif" id="im6"/> <img src="myFocus_white.gif" id="im7"/> <img src="myFocus_white.gif" id="im8"/> </body> </html>
小练习一下
这个练习是有问题的,只能用于单张图片的预加载,这个例子使用了异步调用的方法加载多张图片,要点击多次才能显示全部图片,以后再来完善
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<script type="text/javascript">
var newload= function(){
urlone="http://www.leyoo.com/Public/nImg/Zhuanti/20131231/run_img_"
urllast=".png"
for(var i=1; i<9; i++)
{
url = urlone + i + urllast;
oid = "im"+i;
var tt =function(url,oid){//插入闭包保存数据
imgLoad(url,function(x,y){
//alert(url);
document.getElementById(oid).width = x;
document.getElementById(oid).height = y;
document.getElementById(oid).src = url;
});}(url,oid)
}
}
//var fimg=
var imgLoad = function (url, callback) {
var img = new Image();
img.src = url;
if (img.complete) {
callback(img.width, img.height);
} else {
img.onload = function () {
callback(img.width, img.height);
img.onload = null;
};
};
};
</script>
</head>
<body>
<a onClick="newload()">点击</a>
<img src="myFocus_white.gif" id="im1" />
<img src="myFocus_white.gif" id="im2"/>
<img src="myFocus_white.gif" id="im3"/>
<img src="myFocus_white.gif" id="im4"/>
<img src="myFocus_white.gif" id="im5"/>
<img src="myFocus_white.gif" id="im6"/>
<img src="myFocus_white.gif" id="im7"/>
<img src="myFocus_white.gif" id="im8"/>
</body>
</html>
这个是完善后的,不过加载时的图是本地