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

时间:2015-08-24 00:04:57

标签: javascript

我通过书签将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的情况下执行此操作?

1 个答案:

答案 0 :(得分:0)

使用

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

放置&lt; script&gt;在文档正文末尾包含jQuery的标记,然后在其后添加插件的代码。