Explain Codes LogoExplain Codes Logo

How to include multiple js files using jQuery $.getScript() method

javascript
promises
callbacks
functions
Anton ShumikhinbyAnton Shumikhin·Jan 20, 2025
TLDR

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.js return $.getScript("second.js"); }).then(function() { //second.js is done, let's get third.js return $.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.

function loadScripts(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:

function loadScripts(scripts, progressCallback) { var loaded = 0; scripts.forEach(function(script) { $.getScript(script).then(function() { progressCallback(++loaded / scripts.length); }); }); } loadScripts(["script1.js", "script2.js", "script3.js"], function(progress) { console.log(`Progress: ${(progress * 100).toFixed(2)}% ... loading ${progress == 1 ? 'complete 🏁' : 'in progress ⌛'}`); });

Mix it up, Sequential and parallel

For scripts with dependencies that need to be loaded in order and independent ones that can load in parallel, create a hybrid loading:

$.getScript("main.js", function() { $.when($.getScript("utils.js"), $.getScript("template.js")).done(function() { $.getScript("app.js", function() { console.log("Scripts loaded, here we go!"); }); }); });

Cross-domain scripts

For scripts from different domains, make sure you handle cross-origin requests properly, or you might be left in the cold:

$.ajaxSetup({ crossDomain: true }); $.getScript("//another-domain.com/script.js", function() { console.log("Cross-domain script loaded, we're international now."); });