Questa utilissima libreria javascript non è altro che un piccolo tool che permette di caricare gli script in parallelo ed eseguire codice solo dopo che le dipendenze siano state soddisfatte.
Tramite GitHub possiamo accedere al sorgente
Di seguito qualche esempio per capire come funziona
/ load a single file
loadjs('foo.js', function() {
// foo.js loaded
});
// load multiple files (in parallel)
loadjs(['foo.js', 'bar.js'], function() {
// foo.js & bar.js loaded
});
// load multiple files (in series)
loadjs('foo.js', function() {
loadjs('bar.js', function() {
// foo.js loaded then bar.js loaded
});
});
// add a bundle id
loadjs(['foo.js', 'bar.js'], 'foobar', function() {
// foo.js & bar.js loaded
});
// add a failure callback
loadjs(['foo.js', 'bar.js'],
'foobar',
function() { /* foo.js & bar.js loaded */ },
function(pathsNotFound) { /* at least one path didn't load */ });
// execute a callback after bundle finishes loading
loadjs(['foo.js', 'bar.js'], 'foobar');
loadjs.ready('foobar', function() {
// foo.js & bar.js loaded
});
// .ready() can be chained together
loadjs('foo.js', 'foo');
loadjs('bar.js', 'bar');
loadjs
.ready('foo', function() {
// foo.js loaded
})
.ready('bar', function() {
// bar.js loaded
});
// compose more complex dependency lists
loadjs('foo.js', 'foo');
loadjs('bar.js', 'bar');
loadjs(['thunkor.js', 'thunky.js'], 'thunk');
// wait for multiple depdendencies
loadjs.ready(['foo', 'bar', 'thunk'],
function() {
// foo.js & bar.js & thunkor.js & thunky.js loaded
},
function(depsNotFound) {
if (depsNotFound.indexOf('foo') > -1) {}; // foo failed
if (depsNotFound.indexOf('bar') > -1) {}; // bar failed
if (depsNotFound.indexOf('thunk') > -1) {}; // thunk failed
});
// use .done() for more control
loadjs.ready('my-awesome-plugin', function() {
myAwesomePlugin();
});
loadjs.ready('jquery', function() {
// plugin requires jquery
window.myAwesomePlugin = function() {
if (!window.jQuery) throw "jQuery is missing!";
};
// plugin is done loading
loadjs.done('my-awesome-plugin');
});