1. 程式人生 > >JS/JavaScript前臺非同步載入並呼叫回撥函式

JS/JavaScript前臺非同步載入並呼叫回撥函式

程式碼簡單直接貼程式碼

/**
 * 非同步載入依賴的javascript檔案
 * src:script的路徑
 * callback:當外部的javascript檔案被load的時候,執行的回撥
 */
var loadAsyncScript = function (src, callback) {
	var srcArray = src.split("?")[0].split("/");
	var scr_src = srcArray[srcArray.length - 1];
	
	// 判斷要 新增的指令碼是否存在如果存在則不繼續添加了
	var scripts = document.getElementsByTagName("script");
	if(!!scripts && 0 != scripts.length){
		for(var i = 0; i < scripts.length; i ++){
			if(-1 != scripts[i].src.indexOf(scr_src)){
				callback();
				return true;
			}
		}
	}
	
	// 不存在需要的則新增
	var head = document.getElementsByTagName("head")[0];
	var script = document.createElement("script");
	script.setAttribute("type", "text/javascript");
	script.setAttribute("src", src);
	script.setAttribute("async", true);
	script.setAttribute("defer", true);
	head.appendChild(script);
	
	//fuck ie! duck type
	if (document.all) {
		script.onreadystatechange = function() {
			var state = this.readyState;
			if (state === 'loaded' || state === 'complete') {
				callback();
			}
		}
	} else {
		//firefox, chrome
		script.onload = function() {
			callback();
		}
	}
}