Javascript异步加载js文件并实例化一个对象

Javascript Asynchronous Loading js file and instantiating an object

我正在尝试从另一个 javascript 文件附加一个脚本,我已经按照这个 post 关于非阻塞异步脚本加载 http://calendar.perfplanet.com/2012/the-non-blocking-script-loader-pattern 我已经能够加载外部脚本,但我无法在第二个 js 文件中实例化对象,代码如下:

    (function(url, callback){
       var dom,doc,where,iframe = document.createElement('iframe');
       iframe.src = "javascript:false";
       iframe.id = 'iframeTest';
       (iframe.frameElement || iframe).style.cssText = "border: 0px; z-       index: 50; position: fixed; height: 290px; width: 225px; right: 0px; bottom: 0px;";
       where = document.getElementsByTagName('script');
       where = where[where.length - 1];
       where.parentNode.insertBefore(iframe, where);
       try { 
         doc = iframe.contentWindow.document;
        } catch(e) {
           dom = document.domain;
           iframe.src="javascript:var d=document.open();d.domain='"+dom+"';void(0);";
           doc = iframe.contentWindow.document;
        }
        doc.open()._l = function() {
            var head =                  document.getElementById('iframeTest').contentWindow.document.getElementsByTagName('head')[0];
            var script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = url;
            script.onload = callback;
            head.appendChild(script);           
        }
        doc.write('<body onload="document._l();">');
        doc.close();
     })
     ('http://localhost/js/chat.js', function() { var cb  = new Chatbox('6'); cb.init();} ); 

在我尝试加载的 chat.js 文件中:

      function Chatbox(orgId)
      {
         this.orgId = orgId;
      }
      Chatbox.prototype.constructor = Chatbox;

      Chatbox.prototype.init = function() {
          this.getStatus();
      };
      .....................................

当我尝试加载页面时,我最终收到错误 'Uncaught ReferenceError: Chatbox is not defined'。我知道这里有类似的问题,但找不到在第二个文件中实例化对象的解决方案,尽管如果它不是异步的,它就可以工作。希望我很清楚,任何帮助将不胜感激。提前致谢!

只要在同一域中,您就可以访问 iframe 的对象。否则不行。

document.getElementById('youriframe').contentWindow.cb 

这就是您访问它的方式。您始终可以 运行 在 iframe 本身中编写代码。您可以将其附加到当前 window 并访问它