-1

我发现了一个像这样的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 的异步特性。知道如何解决这个问题吗?

4

1 回答 1

0

您需要在代码中删除这一行:

head.removeChild(script);

否则,script标签会立即再次被删除。

于 2013-08-06T20:55:16.393 回答