在do ... while中注入多个依赖项

时间:2015-11-30 20:19:23

标签: javascript dependency-injection

我尝试在将应用程序挂载到给定节点之前将多个依赖项注入DOM,但它会挂起/崩溃。

function injectSingle (file, done) {
    var source;

    switch (file.type) {
        case 'js':
            source = document.createElement('script');
            source.src = file.src;
            source.async = true;
            break;

        case 'css':
            source = document.createElement('link');
            source.href = file.src;
            source.type = 'text/css';
            source.rel = 'stylesheet';
            break;
    }

    if (source.readyState) { // IE
        source.onreadystatechange = function () {
            if (source.readyState == "loaded" || source.readyState == "complete"){
                source.onreadystatechange = null;
                done();
            }
        };
    } else { // Standard
        source.onload = function () {
            done();
        };
    }

    document.getElementsByTagName('head')[0].appendChild(source);
}

function injectDependencies (files, launch) {
    var ready = 0;
    do {
        injectSingle(files[ready], function () {
            ready++;
            console.log('Ready Count: %s', ready);
        });
    } while (ready < files.length - 1);
    launch();
}

(function () {
    injectDependencies([
        {
            src: '//example.com/dep.min.js',
            type: 'js'
        },
        {
            src: '//example.com/dep.2.js',
            type: 'js'
        },
        {
            src: '//example.com/dep.css',
            type: 'css'
        },
    ], function () {
        React.render(<Application/>, document.getElementById('someId'));
    })
})

请忽略这一点,因为我需要用更多文字填写这篇文章。

Lorem ipsum dolor sit amet,consectetur adipisicing elit,sed do eiusmod tempor incididunt ut labore et dolore magna aliqua。 Ut enim ad minim veniam,quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat。 Duis aute irure dolor in repreptderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur。 Excepteur sint occaecat cupidatat non proident,sunt in culpa qui officia deserunt mollit anim id est laborum。

1 个答案:

答案 0 :(得分:0)

我能够通过将injectDependencies函数更改为此来完成它:

function injectDependencies (files, launch) {
    var script, ready = 0, total = files.length;

    while (script = files.shift()) {
        injectSingle(script, function () {
            ready++;
            if (ready == total) launch();
        });
    }
}