RobbTe
RobbTe

Reputation: 405

getScript, loading multiple scripts in series?

I am trying to load multiple .js files through the GetScript method. I need them to be loaded in series, meaning the first .js files needs to be fully loaded before going to the next one.

Question 1: 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?

Also, I've found that function( data, textStatus, jqxhr ) is a callback function that is executed when the getScript request succeeds. The parameters (data, textStatus, jqxhr) can be used in the funtion, where: data is the data from the .js file, textStatus is the status of the request and jqxhr is a XMLHttpRequest object.

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

Question 3: 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?

jQuery.getScript("//url1.com/file1.js", function(data, textStatus, jqxhr) {
  jQuery.getScript("//url2.com/file2.js", function(data, textStatus, jqxhr) {
    jQuery.getScript("//url3.com/file3.js", function(data, textStatus, jqxhr) {
      jQuery.getScript("//url4.com/file4.js", function(data, textStatus, jqxhr) {
      });
    });
  });
});

Thank you.

Upvotes: 2

Views: 800

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

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

Upvotes: 3

Related Questions