script does not load and dependencies fail

Asked

Viewed 114 times

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 elsewhere), thus preventing other scripts that depend on this will not fail.

  • How do you know it doesn’t carry? it from the 404? Why doesn’t it carry?

1 answer

2


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

If you want to make sure they load in the right order, and without using AMD/Requirejs, you can create a loader of your own that waits for each loader to load.

It would be something like that:

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: http://jsfiddle.net/aq15tapn/

The idea is to have a function to which you pass an array and a callback to be run when the external libraries have loaded all.

The important parts are:

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

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.