簡體   English   中英

在加載另一個腳本之前,如何阻止腳本的執行?

[英]How can I block the execution of a script until another one is loaded?

假設我從主機網頁加載這些腳本:

<script src="http://www.mywebsite.com/widget/widget.js?type=normal" type="text/javascript"></script>
<script src="http://www.mywebsite.com/widget/widget.js?type=rotation" type="text/javascript"></script>

並且我只想在第一個完成時執行第二個(完全;它可以包含異步函數)。

我該怎么做?

您已經做得很好:腳本按照頁面中的集成順序執行,而不是加載。

編輯:正如MaxArt指出的,這可能不是你想要的。 他的答案很好。 但一般來說,你會想要使用javascript常用模式和基於事件的邏輯來避免這種問題:

  • 大多數文件只定義類和函數(其中一些文件將回調作為參數)
  • 有一個main文件啟動它並調用動作序列,異步性通過回調處理。

我的主要代碼通常看起來像這樣:

$(window).ready(function() {
    var myBigEngine = new BigEngine();
    myBigEngine.init(function(){
      // do other things, no need to add other layers as user events and ajax message callback will do the rest
    });
});

嘗試將defer =“defer”屬性應用於第二個<script>聲明

<script src="http://www.mywebsite.com/widget/widget.js?type=rotation" type="text/javascript" defer="defer" ></script>

將整個腳本包裝在一個函數中,如下所示:

(function(id) {
    var id = setInterval(function() {
        if (!window.doneLoading) return;
        clearInterval(id);

        // The whole script file goes here
        ...
    }, 50);
})();

setInterval輪詢(全局,抱歉)變量doneLoading 在第一個腳本中,您必須在完全加載異步函數時將doneLoading設置為true或任何其他非假值,例如在AJAX請求結束時可能?

編輯 :因為我建議在腳本中添加一個全局變量,所以它也可以添加一個全局函數 因此,不是設置setInterval調用,而是將第二個腳本包裝在函數中......但是像這樣:

function doneLoading() {
        // The whole script file goes here
        ...
}

在第一個腳本文件中,在回調函數結束時,只需調用doneLoading()

你可以在window.onload事件中放入第二個腳本init函數

window.onload = function(){

// call function from second script

}

或者使用jQuery

$(function(){

// call function from second script

});

你可以使用此功能添加第二個腳本

function loadScript(src){
    var f=document.createElement('script');
    if(f){
        f.setAttribute("type","text/javascript");
        f.setAttribute("src",src);
        document.getElementsByTagName("head")[0].appendChild(f);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM