script does not load and dependencies fail

2

Sometimes I notice that a script does not load, and the rest of the scripts that somehow use it, end up failing.

What to do to recognize when not loaded and try another alternative (like loading from another place), thus preventing other scripts that rely on this will not fail.

    
asked by anonymous 16.10.2015 / 03:06

1 answer

2

You can use a module manager like AMD / RequireJS that does just that.

If you want to ensure that they load in the right order, and without using AMD / RequireJS, you can create a loader of yours that you expect each load to load.

It would look something like this:

var modulos = [
    'http://code.jquery.com/jquery-1.7.1.js',
    'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js'
];

var carregar = (function () {
    var head = document.getElementsByTagName('head')[0];

    function importar(src, callback) {
        var s = document.createElement('script');
        s.type = "text/javascript";
        s.async = true;
        s.src = src;
        s.addEventListener('load', callback);
        head.appendChild(s);
    }
    return function processador(arr, done) {
        var next = arr.shift();
        if (next) importar(next, function () {
            processador(arr, done);
        });
        else done();
    }
})();

console.log(typeof jQuery); // undefined
carregar(modulos, function(){
    console.log(typeof jQuery); // function
});

jsFiddle: link

The idea is to have a function that passes an array and a callback to be run when the external libraries have loaded all of them.

The important parts are:

  • s.addEventListener('load', callback); that detects when the script has loaded and calls the processor again.

  • var next = arr.shift(); where you will get the next url / script. If there is no more, go to else and call the function done(); which is the callback that was passed to you.

After writing this code found another implementation , slightly more complex .

    
16.10.2015 / 16:05