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
});
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.
How do you know it doesn’t carry? it from the 404? Why doesn’t it carry?
– PauloHDSousa