title: Dynamically Include JavaScript and Wait
body: <p>What I'm trying to do is dynamically include one or more js files from within Javascript. I know there are a bunch of techniques for this, but I'm looking for a solution that follows these rules:</p>
  
  <p>1) Not use any JS frameworks or libraries (jQuery, Prototype, etc).</p>
  
  <p>2) The script should halt execution until the external js file is completely loaded and parsed by the browser.</p>
  
  <p>The rational behind #2 is the external js file will include function definitions that need to be used immediately after the script is included. Most of the time the browser hasn't had time to parse the js file before I start calling those functions.</p>
  
  <p>I don't mind using a callback to know when the script is finished loading, but:</p>
  
  <p>1) I don't know ahead of time how many scripts are going to be dynamically included, so I don't want and can't write a bunch of nested callbacks. I just need to know when they're all finished loading.</p>
  
  <p>2) I'm wording that trying to use some kind of "load" event to fire the callback might not work if the browser has cached the JavaScript.</p>
  
  <p><strong>Edit</strong> I should have mentioned from the start that this is for a plugin system, but I wanted to keep my question/answer generic enough to be helpful to other people.</p>
  
  <p>Users would define which plugins they want to load in an array.</p>
  
  <pre><code>plugins = [ 'FooPlugin', 'BarPlugin' ];
  </code></pre>
  
  <p>I would then loop through the array, and load the js script for each plugin:</p>
  
  <pre><code>for(var i = 0; i &lt; plugins.length; i++) {
      loadScript('plugins/' + plugins[i] + '.js');
  }
  </code></pre>
  
  <p>Each plugin pushes itself onto the loaded_plugins array (This is an example of FooPlugin.js)</p>
  
  <pre><code>load_plugins.push({
      name: 'FooPlugin',
      // Other plugin methods and properties here
  });
  </code></pre>