0
votes

I'm trying to inject multiple dependencies into the DOM before mounting my application on a given node, but it hangs/crashes.

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'));
    })
})

please ignore this bit, as I need to fill this post with more text.

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 reprehenderit 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

1 Answers

0
votes

I was able to accomplish it by changing the injectDependencies function to this:

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

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