一旦条件满足,异步调用函数

Async call a function once condition is met?

本文关键字:异步 调用 函数 满足 条件      更新时间:2023-09-26

我正在通过bookmarklet向页面注入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>

放置<</p>

在文档正文的末尾添加包含jQuery的标签,然后在后面添加插件代码。