[Dynamic JS LOADER]外部jsファイルを動的に呼び出します.


/**
 * Dynamic JS LOADER V0.9
 *
 * @author      :redlz2500 <[email protected]>
 * @version     :DJSLoader.js,v 0.9 2010/02/20 20:35:33 GMT+8:00
 * @description :Dynamic load js file
 * @requirement :ExtJS 3.3.1
 * @comment	    :
 *			ExtJS used:Function.createDelegate(), Ext.get(), Element.remove()
 *			But mootools is better
 * @next version:fireEvent() is great.
 */
 
/**
 * SAMPLE USAGE:
 *
 * var jsloader = new DJSLoader();
 *
 * jsloader.loadJS('js_file_name','js_file_path');
 *
 * jsloader.unloadJS('js_file_name','js_file_path');
 *
 * jsloader.chkJSLoaded('js_file_name','js_file_path');
 *	
 */

DJSLoader=function(){
    this.init=function(opt){};
    this.JS=new Array();
    this.loadJS=function(file,path){
		path=path?path:'';
		var script=document.getElementsByTagName("script");  
		var i,j;
		for (i=0,j=script.length;i<j;i++){  
			if (script[i].getAttribute("src") == (path+file)){  
				return;  
			}  
		} 
		var _script=document.createElement("script");  
		_script.type="text/javascript";  
		_script.src="test.js";  
		var st=new Object();
		st.file=file;
		st.path=path;
		st.loaded=false;
		this.JS.push(st);
		_script.onload=function(obj){
			obj.setJSStatus(file,true,path);
		}.createDelegate(_script,[this]);
		_script.onreadystatechange=function(obj){
			if ( this.readyState=='loaded' || this.readyState=='complete'  ) {
				obj.setJSStatus(file,true,path);
			}
		}.createDelegate(_script,[this]);
		document.getElementsByTagName("head")[0].appendChild(_script); 
	};

	this.setJSStatus=function(file,status,path){
		path=path?path:'';
		var i,j;
		for(i=0,j=this.JS.length;i<j;i++){
			if(this.JS[i].file==file && this.JS[i].path==path){
				this.JS[i].loaded=status;
			}
		}
	}
	
	this.chkJSLoaded=function(file,path){
		path=path?path:'';
		var i,j;
		for(i=0,j=this.JS.length;i<j;i++){
			if(this.JS[i].file==file && this.JS[i].path==path){
				return this.JS[i].loaded;
			}
		}
		return false;
	}

	this.unloadJS=function(file,path){
		path=path?path:'';
		var script = document.getElementsByTagName("script");
		var i,j;
		for(i=0,j=script.length;i<j;i++){  
			if (script[i].getAttribute("src") == (path+file)){  
				var t=Ext.get(script[i]);
				t.remove();
				for(i=0,j=this.JS.length;i<j;i++){
					if(this.JS[i].file==file && this.JS[i].path==path){
						this.setJSStatus(file,false,path);
					}
				}
				return;
			}  
		} 
	}
}