title: Appending scripts to head using javascript - weird behavior
body: <p>The problem I'm trying to solve is an ad loading script, that loads the ad code with jsonp and inserts it into the dom.</p>
  
  <p>Now sometimes the ad code will include javascript tags, and i figured it was just a matter of moving them to the head section and they would run. In theory that works fine but when i made a script to move script tags to the head i ran into some weird behavior.</p>
  
  <p>So I wrote this code to test just the script moving part, eliminating the rest of the code as an error source.</p>
  
  <p>I get the same results, if I have just two scripts in the div it moves one of them, if I have 3 scripts it moves 2 of them. In the code pasted below it moves script 1 and 3, skipping the remote javascript reference and the last script-tag.</p>
  
  <p>Would be interesting to at least know why this happens, and if it can be solved.</p>
  
  <p>Edit: To clarify one thing, if i put the remote jquery script first and one of the simple script tags second it will move the remote script tag to the head fine and skip the second script tag.</p>
  
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html&gt;
  &lt;head&gt;
  &lt;script type="text/javascript"&gt;
  // get div id
  function test() {
  var td = document.getElementById('testId');
  var scripts = td.getElementsByTagName("script");
  console.log("No. of scripts to transfer to head: "+scripts.length);
  for(i=0;i&lt;scripts.length;i++) {
      var curScript = scripts[i];
      document.head.appendChild(curScript);
  }   
  }
  &lt;/script&gt;
  &lt;/head&gt;
  &lt;body onload="test();"&gt;
  &lt;div id="testId"&gt;
      &lt;script type="text/javascript"&gt;var firstScript = 1;&lt;/script&gt;
      &lt;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"&gt;&lt;/script&gt;
      &lt;script type="text/javascript"&gt;var secondScript = 1;&lt;/script&gt;
      &lt;script type="text/javascript"&gt;var thirdScript = 1;&lt;/script&gt;
  &lt;/div&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>