Sequential loading of multiple JS files can be done using nested callbacks and jQuery's $.getScript():
$.getScript("first.js", function() {
$.getScript("second.js", function() {
$.getScript("third.js", console.log.bind(console, "All scripts loaded, time for a coffee break! ☕"));
});
});
This guarantees order, since each script is loaded only after its predecessor is successfully executed.
Conquer multiple js files with style!
Latch onto Promises using $.getScript()
When dealing with multiple scripts, it's smart to use Promises via jQuery. Create promise chains to ensure the scripts execute in order, especially when they are dependent on each other.
$.getScript("first.js").then(function() {
//first.js is done, let's get second.jsreturn $.getScript("second.js");
}).then(function() {
//second.js is done, let's get third.jsreturn $.getScript("third.js");
}).done(function() {
console.log("All scripts loaded in order, domino effect! \ud83d\ude38");
}).fail(function(jqXHR, settings, exception) {
console.error("That's it, apocalypse! Error loading script: "+ exception);
});
Group up Scripts with $.when()
Use jQuery's $.when() to wait for all scripts to load simultaneously. No worries if your scripts are independent and don't care about the order.
$.when(
$.getScript("first.js"),
$.getScript("second.js"),
$.getScript("third.js")
).done(function() {
console.log("All scripts loaded at once, we just went supersonic! 🚀");
}).fail(function() {
console.error("Houston, we have a problem. Some scripts failed to load.");
});
Error handling, the silent hero
Include a .fail()handler to elegantly manage loading errors instead of pretending they never happen.
$.getScript("first.js").then(function() {
return $.getScript("second.js");
}).then(function() {
return $.getScript("third.js");
}).done(function() {
console.log("All scripts loaded and had a coffee break!");
}).fail(function() {
console.error("Error loading one of the scripts, need more coffee...");
});
Script Organiser, your custom helper
Creating a reusable function that loads an array of script URLs and an optional path can rid you of a lot of duplicate code.
functionloadScripts(scriptNames, path = "") {
var promises = scriptNames.map(script => $.getScript(path + script));
return $.when(...promises);
}
loadScripts(["first.js", "second.js", "third.js"], "/path/to/my-scripts/").done(function() {
console.log("Script manager to the rescue. All scripts loaded!");
});
Improving the ride
Track progress, don't walk blindly
When you load a lot of scripts, it's handy to know the progress. A simple counter can help you keep track and provide feedback: