loadjs的改装loadmultijs - 加载多个JS文件

loadmultijs函数是对loadjs的改装,它可以加载多个JS文件,支持回调函数。当多个JS文件全部加载完毕后再执行回调函数。

function loadjs(url,callback){
	var head = document.getElementsByTagName("head")[0];
	var script = document.createElement('script');
	script.onload = script.onreadystatechange = script.onerror = function (){
		if (script && script.readyState && /^(?!(?:loaded|complete)$)/.test(script.readyState)) return;
		script.onload = script.onreadystatechange = script.onerror = null;
		script.src = '';
		script.parentNode.removeChild(script);
		script = null;
		callback();
	}
	script.charset = "gb2312";
	script.src = url;
	try {
		head.appendChild(script);
	} catch (exp) {}
}

function loadmultijs(url,callback){
	if(Object.prototype.toString.call(url)==='[object Array]'){	//是否数组
		this.suc = 0;			//加载计数
		this.len = url.length;	//数组长度
		var a = this;
		for(var i = 0;i < url.length;i++){
			loadjs(url[i],function(){ a.suc++; if(a.suc == a.len) try{callback();}catch(e){} });
		}
	}else if(typeof(url) == 'string'){
		loadjs(url,callback);
	}
}

使用方法:

var url = [
		'ajax.php?ajax=1',
		'functions.js'
	];
loadmultijs(url,function(){ alert("加载完毕。"); /* 这里可以调用动态加载的JS文件的数据或方法 */ });

<完>

你可能感兴趣的:(JavaScript)