加载不同的JavaScript文件

时间:2013-08-06 20:48:08

标签: javascript

我发现了一个像这样的javascript加载函数:

function loadScript(srcs, f) {

    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.src = src;
    var done = false;
    script.onload = script.onreadystatechange = function() {
        // attach to both events for cross browser finish detection:
        if ( !done && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete") ) {
            done = true;
            if (typeof f === 'function') 
                f();
            // cleans up a little memory:
            script.onload = script.onreadystatechange = null;
            head.removeChild(script);
        }
    };
    head.appendChild(script);
};

它非常适合加载一个文件,现在我想修改该函数,以便它可以加载到一个文件数组中。我有这样的代码:

function loadScript(srcs, f) {
    var head = document.getElementsByTagName('head')[0];

    for ( var i = 0; i < srcs.length; i++ ) {
        var script = document.createElement('script');
        script.src = srcs[i];
        var done = false;
        script.onload = script.onreadystatechange = function() {
            // attach to both events for cross browser finish detection:
            if ( !done && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete") ) {
                done = true;
                if (typeof f === 'function') 
                    f();
                // cleans up a little memory:
                script.onload = script.onreadystatechange = null;
                head.removeChild(script);
            }
        };
        head.appendChild(script);
    }
};

现在如果我这样调用这个函数:

loadScript( ['testing_path1', 'testing_path2'], function() {


} );

即使加载了testing_path2文件,我也无法调用其中的函数。我在想它是因为javascript的异步功能。知道如何解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

您需要在代码中删除此行:

head.removeChild(script);

否则会立即删除script标记。