title: Detect when list of scripts are all loaded in javascript (Using namespaces).
body: <p>I have made a namespaces framework for javascript. I am loading some plugins (.js files) which are dynamically added to the HTML.</p>
  
  <p>I am going to try to simplify the code.</p>
  
  <p>This function is used to dinamically load a JS. The callback function is called after .js file has been loaded. Consider that the following code has already been run.</p>
  
  <pre><code>MYNAMESPACE.plugins = ["plugin1", "plugin2"];
  MYNAMESPACE.getJS = {
      get: function (url, callback) {
          var script = document.createElement("script");
          var head = document.getElementsByTagName('head')[0];
          script.type = "text/javascript";
          script.src = url;
          head.insertBefore(script, head.firstChild)
          script.onload = callback;
          script.onreadystate = callback;
          return script;
          }
  };
  </code></pre>
  
  <p>I have a init function that loads the plugins contained in MYNAMESPACE.plugins as follows: </p>
  
  <pre><code>MYNAMESPACE.init = function (callback) {
      for (index in MYNAMESPACE.plugins) {
          plugin = MYNAMESPACE.plugins[index];
          MYNAMESPACE.getJS.get(plugin + '.js', function ()
           {
                // This callback is executed when the js file is loaded
           });
      }
      // Here I want to execute callback function, but after all the callbacks in the for loop have been executed.  Something like: if (alljsloaded) callback();
  }
  </code></pre>
  
  <p>In my HTML I have the following script tag:</p>
  
  <pre><code>&lt;html&gt;
      &lt;head&gt;
      &lt;script type="text/javascript"&gt;
          $(document).ready(function () {
              MYNAMESPACE.init(); 
  
              // The following line is not executed correctlybecause init finished before the scripts are loaded and the functionOnPlugin1 is undefined.
              MYNAMESPACE.functionOnPlugin1();
          });
      &lt;/script&gt;
      &lt;/head&gt;
      &lt;body&gt;
      &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>And I want to change it for something like this:</p>
  
  <pre><code>&lt;html&gt;
      &lt;head&gt;
      &lt;script type="text/javascript"&gt;
          $(document).ready(function () {
              MYNAMESPACE.init(function() { MYNAMESPACE.functionOnPlugin1(); });  
          });
      &lt;/script&gt;
      &lt;/head&gt;
      &lt;body&gt;
      &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>But I don't know how to modify the function MYNAMESPACE.init() so it executes the callback after ALL the plugin scripts are loaded. </p>
  
  <p>Any ideas? Maybe using closures.</p>