非同步載入js並判斷是否載入成功,類似jq的getScript()
阿新 • • 發佈:2019-01-27
(1) defer,只支援IE
(2) async:
(3) 建立script,插入到DOM中
/** * 非同步載入依賴的javascript檔案 * src:script的路徑 * callback:當外部的javascript檔案被load的時候,執行的回撥 */ function loadAsyncScript(src, callback) { 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); if (script.readyState) {//ie script.onreadystatechange = function() { var state = this.readyState; if (state === 'loaded' || state === 'complete') { callback(); } } } else {//Others: Firefox, Safari, Chrome, and Opera script.onload = function() { callback(); } } }
寫法2:
//非同步載入js function loadScript(url,callback){ var script = document.createElement("script"); script.type="text/javascript"; if(script.readyState){ script.onreadystatechange = function(){ if(script.readyState=="loaded"||script.readyState=="complete"){ script.onreadystatechange=null; callback(); } } }else{ script.onload = function(){ callback(); } } script.src = url; document.getElementsByTagName("head")[0].appendChild(script); }
jq寫法:
$.getScript("xxx.js", function(){
alert("xxx.js載入完畢")
});