How to Include Multiple Js Files Using Jquery $.Getscript() Method

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

The answer is

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

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

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

});

FIDDLE

ANOTHER FIDDLE

In the above code, adding a Deferred and resolving it inside $() is like placing any other function inside a jQuery call, like $(func), it's the same as

$(function() { func(); });

i.e. it waits for the DOM to be ready, so in the above example $.when waits for all the scripts to be loaded and for the DOM to be ready because of the $.Deferred call which resolves in the DOM ready callback.



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 = [
'myscript1.js',
'myscript2.js',
'myscript3.js'
];

$.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
});

Import multiple files using jQuery.getScript

You can call the getScript() method 3 times or as many times as the number of script files you want to import.

getScript, loading multiple scripts in series?

I was using the code below, but found that this becomes quite messy when the amount of js files increase. Is there a more clear way of loading multiple .js files?

You could DRY it up a little by recursively iterating through an array of URLs, assuming that no further processing is required in the callback. Something like this:

function getScript(arr, i) {
i = i || 0;
jQuery.getScript(arr[i], function() {
i++;
arr.length > i && getScript(arr, i);
});
}
getScript(['//url1.com/file1.js', '//url2.com/file2.js', '//url3.com/file3.js', '//url4.com/file4.js']);

Why is the parameter textStatus used as a callback? Using it in this function will always set it to Success, right?

It follows the same pattern as other jQuery AJAX methods, you're right that in this case it will always be a successful response.

When I only want to execute the next getScript, i could just leave out the parameters and write: jQuery.getScript("url.min.js", function() { Correct?

Yes

How to Dynamically Load Internal Scripts In Order With Javascript

getScript returns a Promise-like object, so you can await each call of it in a loop for them to be processed in serial:

(async () => {
for (const path of ['/1.js', '/2.js', '/3.js']) {
await $.getScript(path);
}
// Do something
})()
.catch((err) => {
// Something went wrong
});

Load Multiple Javascript files in serial

another suggestion is to use jQuery.Deferred() this way:

var d1 = new $.Deferred();
var d2 = new $.Deferred();
var d3 = new $.Deferred();
var d4 = new $.Deferred();

$.when( d1, d2, d3, d4 ).done(function () {
console.log('Loaded in order.');
});

d1.resolve($.getScript("/assets/libs/swal/sweet-alert.min.js"));
d2.resolve($.getScript("/assets/js/jquery.form.js"));
d3.resolve($.getScript("/assets/js/jquery.preloader.js"));
d4.resolve($.getScript("/assets/js/item_inventory.js"));

To load and initialize multiple JS plugins on specific page in jQuery

it is because daterangepicker.js not yet loaded, execute the script in callback or done() function.

if ($(".section").length) {
var script_arr = [
'moment.js',
'daterangepicker.js',
];
$.getMultiScripts(script_arr).done(function() {
$('#date-picker').daterangepicker({
"opens": "left",
singleDatePicker: true,
isInvalidDate: function(date) {
var disabled_start = moment('09/02/2018', 'MM/DD/YYYY');
var disabled_end = moment('09/06/2018', 'MM/DD/YYYY');
return date.isAfter(disabled_start) && date.isBefore(disabled_end);
}
});
});
}

Do I need to call $.getScript multiple times?

By default the $.getScript() function mangles the cache - meaning that each time it is executed the file will be fetched again. This is useful only if the js file is not a static js-file, i.e if it contains some server-side code (such as PHP) which customizes the data according to some other data available to the session.

If you have a static js file, which it appears that you have, you can disable this behaviour by doing

$.ajaxSetup({
cache: true
});

(note though that this is global for all ajax calls).

You do not need to reload the script with another $.getScript() if your script is a static file. And if you do not try to reload it, there is no need to enable AJAX caching either.

There is one exception to not needing to reload the script even if it is static though: If the MAP script stores some information which is not reset when you do initMap. That would be bad design, but it could be the case in a script.



Related Topics



Leave a reply



Submit