title: Why does appending a <script> to a dynamically created <iframe> seem to run the script in the parent page?
body: <p>I'm attempting to create an &lt;iframe&gt; using JavaScript, then append a &lt;script&gt; element to that &lt;iframe&gt;, which I want to run in the context of the &lt;iframe&gt;d document.</p>
  
  <p>Unfortunately, it seems I'm doing something wrong - my JavaScript appears to execute successfully, but the context of the &lt;script&gt; is the parent page, not the &lt;iframe&gt;d document. I also get a 301 Error in Firebug's "Net" tab when the browser requests <strong>iframe_test.js</strong>, though it then requests it again (not sure why?) successfully.</p>
  
  <p>This is the code I'm using (live demo at <a href="http://onespot.wsj.com/static/iframe_test.html" rel="noreferrer">http://onespot.wsj.com/static/iframe_test.html</a>):</p>
  
  <p><strong>iframe_test.html</strong></p>
  
  <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;
  &lt;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"&gt;
    &lt;head&gt;
      &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8"/&gt;
      &lt;title&gt;&amp;lt;iframe&amp;gt; test&lt;/title&gt;
    &lt;/head&gt;
    &lt;body&gt;
      &lt;div id="bucket"&gt;&lt;/div&gt;
      &lt;script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"&gt;&lt;/script&gt;
      &lt;script type="text/javascript"&gt;
        $(document).ready(function() {
          $('#bucket').append('&lt;iframe id="test"&gt;&lt;/iframe&gt;');
          setTimeout(function() {
            var iframe_body = $('#test').contents().find('body');
            iframe_body.append('&lt;scr' + 'ipt type="text/javascript" src="http://onespot.wsj.com/static/iframe_test.js"&gt;&lt;/scr' + 'ipt&gt;');
          }, 100);
        });
      &lt;/script&gt;
    &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p><strong>iframe_test.js</strong></p>
  
  <pre><code>$(function() {
    var test = '&lt;p&gt;Shouldn\'t this be inside the &amp;lt;iframe&amp;gt;?&lt;/p&gt;';
    $('body').append(test);
  });
  </code></pre>
  
  <p>One thing that seems unusual is that the the code in <strong>iframe_test.js</strong> even works; I haven't loaded jQuery in the &lt;iframe&gt; itself, only in the parent document. That seems like a clue to me, but I can't figure out what it means.</p>
  
  <p>Any ideas, suggestions, etc. would be much appreciated!</p>