閱讀933 返回首頁    go 阿裏雲 go 技術社區[雲棲]


如何判斷js腳本加載完成

在“按需加載”的需求中,我們經常會判斷當腳本加載完成時,返回一個回調函數,那如何去判斷腳本的加載完成呢?

我們可以對加載的 JS 對象使用 onload 來判斷(js.onload),此方法 Firefox2、Firefox3、Safari3.1+、Opera9.6+ 瀏覽器都能很好的支持,但 IE6、IE7 卻不支持。曲線救國 —— IE6、IE7 我們可以使用 js.onreadystatechange 來跟蹤每個狀態變化的情況(一般為 loading 、loaded、interactive、complete),當返回狀態為 loaded 或 complete 時,則表示加載完成,返回回調函數。

對於 readyState 狀態需要一個補充說明:

1.在 interactive 狀態下,用戶可以參與互動。
2.Opera 其實也支持 js.onreadystatechange,但他的狀態和 IE 的有很大差別。

 

<script>

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;
}


include_js('https://www.planabc.net/wp-includes/js/jquery/jquery.js');


</script>

最後更新:2017-04-02 17:28:36

  上一篇:go Android:實現一種浮動選擇菜單的效果
  下一篇:go Hibernate HelloWorld(第一步)