title: Dynamically load jQuery in IE and Chrome
body: <p>I'm creating an external widget that uses jQuery and rather than have the user include it separately I'd like to check to see if it's loaded and load it dynamically if it's not.</p>
  
  <p>Problem is I need to wait until it's loaded to execute the rest of the script, which requires event handlers that IE and FF/Chrome handle differently.</p>
  
  <p>If I do this, it works fine in IE8:</p>
  
  <pre><code>&lt;div id="test"&gt;
  &lt;p&gt;This is a test.&lt;/p&gt;
  &lt;/div&gt;
  
  &lt;script&gt;
  if (typeof jQuery == 'undefined') {
      s = document.createElement("script");
      s.src = "//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js";
      if (s.addEventListener) {
          s.addEventListener("load", runScript, false);
      } else if (s.readyState) {
          s.onreadystatechange = runScript;
      }
  
  } else {
      runScript();
  }
  
  function runScript() {
      document.getElementsByTagName('head')[0].appendChild(s);
      $('#test').css('font-size', '50px');
  
  }
  &lt;/script&gt;
  </code></pre>
  
  <p>But that doesn't work in Chrome. However if I append the script earlier, it works in Chrome but not IE:</p>
  
  <pre><code>&lt;div id="test"&gt;
  &lt;p&gt;This is a test.&lt;/p&gt;
  &lt;/div&gt;
  
  &lt;script&gt;
  if (typeof jQuery == 'undefined') {
      s = document.createElement("script");
      s.src = "//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js";
      document.getElementsByTagName('head')[0].appendChild(s);
      if (s.addEventListener) {
          s.addEventListener("load", runScript, false);
      } else if (s.readyState) {
          s.onreadystatechange = runScript;
      }
  
  } else {
      runScript();
  }
  
  function runScript() {
  
      $('#test').css('font-size', '50px');
  
  }
  &lt;/script&gt;
  </code></pre>
  
  <p>Any ideas on how to dynamically load jQuery with event handlers that works both in IE and Chrome?</p>
  
  <p><strong>EDIT:</strong> Changed appendChild target from test to head.</p>