1

Say I have the following array:

var array=['script1.js', 'script2.js','script3.js','script1.js']

How can I run through that array loading in each script one by one with the next one only being called after the previous one has been fully loaded and fired?

I wish to use JQuery's getScript function.

Would something like this suffice?

var i=0;
var id_key='file'+i;
function load_script(url){
$.getScript(url)
.done(i++; load_script(array[i]);
}
5
  • 2
    Close, but no cigar! You'll need a function call in done() Commented Dec 28, 2013 at 13:21
  • A function call to what? Commented Dec 28, 2013 at 13:37
  • $.getScript(url,function(){//load next}); Commented Dec 28, 2013 at 13:40
  • According to the Jquery site: "Success Callback The callback is fired once the script has been loaded but not necessarily executed.". Is there a way around that? Commented Dec 28, 2013 at 13:42
  • @Nuvolari By the time, next request succeeds, the previously loaded script would most probably have executed, so is that an issue that your callback get called before the loaded script is executed? Commented Dec 28, 2013 at 13:51

2 Answers 2

3

Try something like

var array = ['script1.js', 'script2.js', 'script3.js', 'script1.js'];

function load_scripts(array) {
    if (!array || !array.length) {
        return
    }
    $.getScript(array.shift(), function () {
        load_scripts(array);
    })
}
load_scripts(array)

Demo: Fiddle

Sign up to request clarification or add additional context in comments.

Comments

1
var i=1;
var id_key='file'+i;
function load_script(url){
  $.getScript(url)
  .done(
      function(data){
        switch(i){
          case 1://do blah blah
          case 2://do blah blah
        }
        i++;
        if(i<=array.length){
          load_script(array[i])
        }
      });
}
load_script(array[i]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.