title: Cross-browser javascript loading with callback: Is there a better way than using iframes?
body: <p>I want to programmatically load a .js file and do some stuff when it's finished loading. The file I want to include is hosted on the domain where it will be included.</p>
  
  <p>Specifically, the file I'm loading is swfobject.js. I want to check for its existence and load it only if needed.</p>
  
  <p>Here's what I have so far:</p>
  
  <pre><code>// BHD is defined elsewhere. For this example:
  var BHD = {};
  
  BHD.uid = function () {
    return 'x'+(+(''+Math.random()).substring(2)).toString(32)+(+new Date()).toString(32);
  };
  
  BHD.include = function (file, callback) {
    var uid = BHD.uid();
    frame = document.createElement('iframe');
    frame.src = file;
    frame.id = frame.name = uid;
    frame.onload = function () {
      var s = document.getElementsByTagName('script')[0]; 
      var d = frames[uid].document.documentElement;
      var script = document.createElement('script');
      script.type = 'text/javascript';
      script.text = d.textContent||d.innerText;
      s.parentNode.insertBefore(script, s);
      callback();
      s.parentNode.removeChild(s);
      frame.parentNode.removeChild(frame);
    }
    document.documentElement.appendChild(frame);
  }
  </code></pre>
  
  <p>This seems to work. It's an ugly hack, though. The contents of the .js file is loaded in an iframe, and when the iframe is finished loading, a new script element is injected into the main document with the contents of the iframe. This seems to make the script load immediately, so the callback can be called immediately afterward.</p>
  
  <p>I am wondering if there is a better way to do this. I'm looking for something along the lines of a cross-browser 'onload' event for script tags, or some other way to avoid the iframe hack. </p>