破釜沉舟论坛 » WEB 开发 » [javascript]最近写的一个简单的图片预载对象

2006-11-3 11:33 niss
[javascript]最近写的一个简单的图片预载对象

比较简单,大家看看有什么可以改进的
[code]
ImageLoader = function(start,complete,urls){
this.start = start;
this.complete = complete;
this.urls = urls;
this.hint = "图片";
this.totle = urls.length;
this.achieve = 0;
this.failure = 0;
this.percent = 0;
this.load();
}
ImageLoader.prototype = {
load : function(){
  var img = new Image();
  var oThis = this;
  img.onload = function(){
   oThis.achieve += 1;
   oThis.percent = Math.round(((oThis.achieve+oThis.failure)/oThis.totle)*100);
   oThis.complete.apply(oThis,[this.src,true,oThis.percent]);
   this.onload  = null;//清除回调,避免gif循环载入
   this.onerror = null;
   if(oThis.percent<100){
    oThis.load();
   }
  }
  img.onerror = function(){
   oThis.failure += 1;
   oThis.percent = Math.round(((oThis.achieve+oThis.failure)/oThis.totle)*100);
   oThis.complete.apply(oThis,[this.src,false,oThis.percent]);
   this.onerror = null;
   this.onload  = null;
   if(oThis.percent<100){
    oThis.load();
   }
  }
  if(this.urls.length>0){
   var url = this.urls.shift();
   img.src = url;//载入图片
  }
}
}
[/code]

使用方法:
首先要定义两个回调函数,一个是预载开始时的回调
function startCallback(){
   var div = document.getElementById("loadingDiv");
   div.innerHTML  = "图片加载中......";
}
另一个是当某个图片加载完成(或失败)后的回调
function completeCallback(sCurrentObject,bAchieveTag,iPercent){
   var text = (bAchieveTag)?"加载完成":"加载失败";
   var div = document.getElementById("loadingDiv");
   div.innerHTML += "<br/>"+sCurrentObject+text+" 进度:"+iPercent+"%";
   if(iPercent==100){
      div.innerHTML += "<br/>"+this.hint+"加载完毕";
   }
}

预载图片:new ImageLoader(startCallback,completeCallback,["1.gif","5.gif","out.gif","./img/logon.gif"]);

页: [1]


Powered by Discuz! Archiver 5.5.0  © 2001-2006 Comsenz Inc.