//(function(){
var LoadManager=function()
{
this.resource;
this.loaded=0;
this.total;
this.finish=false;
this.percent=0;
this.image=[];   //存储载入的所有图片,其下表为其ID号
this.audio=[];
this.img;      //用于临时存储图片
this.ado;
this.id;
};LoadManager.prototype._load=function(props){
var id,type,size,src;
for(i in props)
{
if(i=="id")
   this.id=id=props[i];
if(i=="type")
   type=props[i];
if(i=="size")
   size=props[i];
if(i=="src")
   src=props[i];
}
if(type=="img")
{
this.img = new Image();
this.img.addEventListener("loaded", this._imgLoadedCallBack, false);
this.img.src=src;
}

else if(type=="audio")
{
this.ado = new Audio(src);
        this.ado.addEventListener("canplay", this._audioCanplayCallBack, false);
        this.ado.addEventListener("error", this._audioErrorCallBack, false);
        this.ado.load();

}
};
LoadManager.prototype._imgLoadedCallBack=function(){
this.image[this.id]=this.img;
this.loaded++;
this.percent=this.loaded/this.total*100;
if(this.percent==100)
   this.finish=true;
};
LoadManager.prototype._audioCanplayCallBack=function(){
this.audio[this.id]=this.ado;
this.imgLoadedCallBack();
};
LoadManager.prototype.loadAll=function(r){     //此处要求传入一个对象数组  其结构为 id  type  size  src ,id号是所有资源的唯一标识
this.resource=r;
this.total=this.resource.length;
for(var i=0;i<this.resource.length;i++)
{
this._load(this.resource[i]);
}
};

解决方案 »

  1.   

    代码如上,相用这个类在显示页面之前加载图片和音乐,但不知道怎么老是加载不成功。this.img.src=src;不是对img设置src就会开始加载么?this.ado.load();不可以加载音乐么?
      

  2.   

    一 你可以在加载前display: none;整个document
    二 你可以把img放到body最开头 等img onload后再删除img元素 再把下面的元素加载 之前的图片浏览器加载过应该有缓存 就不用担心重新载入的速度其实不太清楚你想做什么
      

  3.   

    (function(){

    var ImageLoader = function(images,loading,complete){
    /*
     *  images数据格式如下[{id:img1,src:image1.jpg,size:34},{id:img2,src:image2.jpg,size:50}]
     */
    this.countTotal = images.length;
    this.img = [];
    this.images = images;
    this.loading = loading;
    this.complete = complete;
    for(var i = 0;i < this.countTotal;i++){
    var imgObj = new Image();
    this.img.push(imgObj);
    }
    this.loadingIndex = 0;
    }
    ImageLoader.prototype.startLoader = function(){
    this._loadNext(this.loadingIndex);
    }

    ImageLoader.prototype._loadNext = function(index){
    this.img[index].src = this.images[index].src;
    var self = this;
    this.img[index].onload = function(){
    self.loading(this);
    if(self.loadingIndex < self.countTotal-1){
    self.loadingIndex++;
    self._loadNext(self.loadingIndex);
    }else{
    self.complete();
    }
    }
    }
    window['ImageLoader'] = ImageLoader;
    }());可以预加载图片 loading为没加载一张图片触发的方法  complete为全部加载后执行的方法。具体你可以再扩展下。