js 判斷指令碼載入完畢的代碼

來源:互聯網
上載者:User

複製代碼 代碼如下:
if(this.isIE) {
js.onreadystatechange=function(){if(js.readyState=="loaded" || js.readyState=="complete") callback();}
}else{js.onload=function(){callback();}}
js.onerror=function(){alert('Not Found (404): '+src)}//chrome


JS判斷指令碼是否載入完成

在“按需載入”的需求中,我們經常會判斷當指令碼載入完成時,返回一個回呼函數,那如何去判斷指令碼的載入完成呢?
我們可以對載入的 JS 對象使用 onload 來判斷(js.onload),此方法 Firefox2、Firefox3、Safari3.1+、Opera9.6+ 瀏覽器都能很好的支援,但 IE6、IE7 卻不支援。曲線救國 —— IE6、IE7 我們可以使用 js.onreadystatechange 來跟蹤每個狀態變化的情況(一般為 loading 、loaded、interactive、complete),當返回狀態為 loaded 或 complete 時,則表示載入完成,返回回呼函數。
對於 readyState 狀態需要一個補充說明:
在 interactive 狀態下,使用者可以參與互動。
Opera 其實也支援 js.onreadystatechange,但他的狀態和 IE 的有很大差別。
具體實現代碼如下:
複製代碼 代碼如下:
function include_js(file) {
var _doc = document.getElementsByTagName('head')[0];
var js = document.createElement('script');
js.setAttribute('type', 'text/javascript');
js.setAttribute('src', file);
_doc.appendChild(js);
if (!/*@cc_on!@*/0) { //if not IE
//Firefox2、Firefox3、Safari3.1+、Opera9.6+ support js.onload
js.onload = function () {
alert('Firefox2、Firefox3、Safari3.1+、Opera9.6+ support js.onload');
}
} else {
//IE6、IE7 support js.onreadystatechange
js.onreadystatechange = function () {
if (js.readyState == 'loaded' || js.readyState == 'complete') {
alert('IE6、IE7 support js.onreadystatechange');
}
}
}
return false;
}
//execution function
include_js('http://www.jb51.net/jslib//jquery/jquery.js');

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.