Question

I am loading multiple scripts of a plugin via get $.getScript, and I should only initiate the plugin after the last load of the script, but how can I know when the loop reaches the last one?

// load multiple files.
var scripts = [
    'mode/xml/xml.js',
    'mode/css/css.js',
    'mode/javascript/javascript.js'
];

alert(scripts.length); // 3

for(var i = 0; i < scripts.length; i++) 
{
    $.getScript(http_root+'global/views/javascripts/codemirror/original/'+scripts[i], function() {

        alert(i); // this will alert number 3 for 3 times.

        if(i == scripts.length) // this means that the plugin will be initiated 3 times.
        {
            var editor = CodeMirror.fromTextArea(document.getElementById("code_content_1"), { 
                mode: "text/html", 
                theme: "eclipse",
                lineNumbers: true
            });
        }
    });

    alert(i); // this will alert the number from 0 to 2.
}

any ideas?

Was it helpful?

Solution

Wrap call in closure so that variable i wont change on every iteration.

for(var i = 0; i < scripts.length; i++) 
{
  (function(i) {
      $.getScript(http_root+'global/views/javascripts/codemirror/original/'+scripts[i], function() {

      if(i + 1 == scripts.length)
      {
        var editor = CodeMirror.fromTextArea(document.getElementById("code_content_1"), { 
            mode: "text/html", 
            theme: "eclipse",
            lineNumbers: true
        });
      }
    });
  })(i);  
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top