JavaScript - JSLoader.js

 

/**
 * js動態加載器
 * @class ScriptLoader.prototype
 * @extends Ext.Window
 * @author nb
 * @version 20110812
 */


ScriptLoader = function() {
 this.timeout = 30;
 this.scripts = [];
 this.disableCaching = false;
 this.loadMask = null;
};
ScriptLoader.prototype = {
 showMask : function() {
  if (!this.loadMask) {
   this.loadMask = new Ext.LoadMask(Ext.getBody());
   this.loadMask.show();
  }
 },
 hideMask : function() {
  if (this.loadMask) {
   this.loadMask.hide();
   this.loadMask = null;
  }
 },
 processSuccess : function(response) {
  this.scripts[response.argument.url] = true;
  window.execScript ? window.execScript(response.responseText) : window
    .eval(response.responseText);
  if (response.argument.options.scripts.length == 0) {
   this.hideMask();
  }
  if (typeof response.argument.callback == 'function') {
   response.argument.callback.call(response.argument.scope);
  }
 },
 processFailure : function(response) {
  this.hideMask();
  Ext.MessageBox.show( {
   title : '提示',
   msg : '抱歉,加載失敗! 錯誤代碼:#1527',
   closable : false,
   icon : Ext.MessageBox.ERROR,
   minWidth : 200
  });
  setTimeout(function() {
   Ext.MessageBox.hide();
  }, 3000);
 },
 load : function(url, callback) {
  var cfg, callerScope;
  if (typeof url == 'object') { // must be config object   
  cfg = url;
  url = cfg.url;
  callback = callback || cfg.callback;
  callerScope = cfg.scope;
  if (typeof cfg.timeout != 'undefined') {
   this.timeout = cfg.timeout;
  }
  if (typeof cfg.disableCaching != 'undefined') {
   this.disableCaching = cfg.disableCaching;
  }
 }
 if (this.scripts[url]) {
  if (typeof callback == 'function') {
   callback.call(callerScope || window);
  }
  return null;
 }
 this.showMask();
 Ext.Ajax.request( {
  url : url,
  success : this.processSuccess,
  failure : this.processFailure,
  scope : this,
  timeout : (this.timeout * 1000),
  disableCaching : this.disableCaching,
  argument : {
   'url' : url,
   'scope' : callerScope || window,
   'callback' : callback,
   'options' : cfg
  }
 });
}
};


ScriptLoaderMgr = function() {
 this.loader = new ScriptLoader();
 this.load = function(o) {
  if (!Ext.isArray(o.scripts)) {
   o.scripts = [ o.scripts ];
  }
  o.url = o.scripts.shift();
  if (o.scripts.length == 0) {
   this.loader.load(o);
  } else {
   o.scope = this;
   this.loader.load(o, function() {
    this.load(o);
   });
  }
 };
};


JSLoader = new ScriptLoaderMgr();


//使用方式
//JSLoader.load({   
//    scripts: ["1.js", "2.js", "3.js"], //地址數據,用到幾個傳幾個地址  
//    callback: function() {
//  //加載成功後的一系列操作,此函數可以去除
//    }
//});

發佈了21 篇原創文章 · 獲贊 3 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章