title: Load multiple script files and have them parsed in order / synchonously
body: <p>I've come across similar questions but I think I have a small variation on this: I have a list of files I want to be able to load but <strong>some are dependent on eachother</strong> so the order in which they load - or actually parsed and executed - matters.</p>
  
  <p>Simplified code of what I have now:</p>
  
  <pre><code>function loadscripts() {
      for (var i=0; i&lt;list.length; i++) {
          var scriptElem = document.createElement("script");
          scriptElem.src = list[i];
          $("body").append(scriptElem);
  }
  
  var list ["script1.js","script2.js"];
  
  loadscripts();
  </code></pre>
  
  <p>I assumed that, because I'm basically adding  tags to the DOM, the browser will parse them in order like it does when they would be there in the 'static' html file. But it turns out it doesn't.</p>
  
  <p>For example, I load hammerjs and its jquery hammer plugin. These are separate files so I add them to the dom in order but the jquery hammer plugin will sometimes throw an error (Hammer is undefined) when it is parsed before hammerjs.</p>
  
  <p>So something like this is not safe to use:</p>
  
  <pre><code>// script1.js
  var someObject = {
      value1:1, value2:2
  }
  
  // script2.js
  console.log(someObject.value1);
  </code></pre>
  
  <p>This will (sometimes!) throw an error, something like "can not access 'value1' of undefined".</p>
  
  <p>I could, like the similar questions and their answers here on SO point out, use script.onload but since I have multiple files I want to load that would require to keep track of which file is loaded, call the loadScript function again and add the next, and so on.. That would be a bit of a mess.</p>
  
  <p>Does anyone know a solution that would work that is as clean as possible?</p>
  
  <p>Related questions:</p>
  
  <ul>
  <li><a href="https://stackoverflow.com/questions/6074833/load-and-execute-javascript-code-synchronously">Load and execute javascript code SYNCHRONOUSLY</a></li>
  <li><a href="https://stackoverflow.com/questions/3248384/document-createelementscript-synchronously/">document.createElement(“script”) synchronously</a></li>
  </ul>