sozhen sozhen - 5 months ago 329x
Javascript Question

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

I am trying to dynamically include javascript files into my js file. I did some research about it and find jQuery $.getScript() method would be a desired way to go.

// jQuery
$.getScript('/path/to/imported/script.js', function()
// script is now loaded and executed.
// put your dependent JS here.
// what if the JS code is dependent on multiple JS files?

But I am wondering whether this method can load multiple scripts at one time? Why I am asking this is because sometimes my javascript file is depending on more than one js files.

Thank you in advance.


TL, DR, the answer

You can use promises with getScript() and wait until all the scripts are loaded, something like:

    $.getScript( "/mypath/myscript1.js" ),
    $.getScript( "/mypath/myscript2.js" ),
    $.getScript( "/mypath/myscript3.js" ),
    $.Deferred(function( deferred ){
        $( deferred.resolve );

    //place your code here, the scripts are all loaded




For more generic use, a handy function

A utility function that accepts any array of scripts could be created like this :

$.getMultiScripts = function(arr, path) {
    var _arr = $.map(arr, function(scr) {
        return $.getScript( (path||"") + scr );

    _arr.push($.Deferred(function( deferred ){
        $( deferred.resolve );

    return $.when.apply($, _arr);

which can be used like this

var script_arr = [

$.getMultiScripts(script_arr, '/mypath/').done(function() {
    // all scripts loaded

where the path will be prepended to all scripts, and is also optional, meaning that if the array contain the full URL's one could also do this, and leave out the path all together

$.getMultiScripts(script_arr).done(function() { ...

Arguments, errors etc.

As an aside, note that the done callback will contain a number of arguments matching the passed in scripts, each argument representing an array containing the response

$.getMultiScripts(script_arr).done(function(response1, response2, response3) { ...

where each array will contain something like [content_of_file_loaded, status, xhr_object]. We generally don't need to access those arguments as the scripts will be loaded automatically anyway, and most of the time the done callback is all we're really after to know that all scripts have been loaded, I'm just adding it for completeness, and for the rare occasions when the actual text from the loaded file needs to be accessed, or when one needs access to each XHR object or something similar.

Also, if any of the scripts fail to load, the fail handler will be called, and subsequent scripts will not be loaded

$.getMultiScripts(script_arr).done(function() {
     // all done
}).fail(function(error) {
     // one or more scripts failed to load
}).always(function() {
     // always called, both on success and error