簡體   English   中英

一旦滿足條件,異步調用函數?

[英]Async call a function once condition is met?

我通過書簽將jQuery和一些jQuery插件注入頁面。 必須在jQuery完成加載后才能啟動插件。 否則,我將得到一個錯誤,“未定義jQuery”。 因此,我需要一種將其延遲到那時的方法。

目前,我正在使用setInterval。 它一直循環直到滿足條件,然后創建下一個腳本。

函數調用

injectScript('https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js');
injectScript('http://www.jnathanson.com/blog/client/jquery/heatcolor/jquery.heatcolor.0.0.1.pack.js', function(){return typeof jQuery != 'undefined'});

功能定義

function injectScript(src, dependency){
    /* Description: creates a new script within the DOM         */

    /* Syntax:                                                  */

    /* src                                                      */
    /*       contains a string to the link location of          */
    /*       the script.                                        */

    /* dependency                                               */
    /*       a function that returns true when all dependent    */
    /*       scripts are finished loading.                      */


    scriptLoad.total++;
    dependency = dependency || function(){return true};




    var depenLoop = setInterval(function(){ /* Wait for dependencies to finish loading, then create the script */
        if(dependency()){
            clearInterval(depenLoop);

            var script    = document.createElement('script');
            script.onload = function(){ scriptLoad.ready++; };  /* onload must be set before src, otherwise src could */
            script.src    = src;                                /* finish early and onload would never fire.          */
            document.body.appendChild(script);

        }/*end if*/
    }, 100);/*loop*/
}/*end function*/

混亂,但是此代碼有效。 但是,我正在尋找更好的解決方案。 還有其他方法可以不使用setInterval和純JS來做到這一點嗎?

采用

<script src="jquery.js"></script>
<script>
$(function(){
    // Code to execute after jQuery has loaded
});
</script>
</body>

將包含jQuery的<script>標記放在文檔主體的末尾,然后在其后添加插件代碼。

暫無
暫無

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

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