【问题标题】:how to load javascript dynamically如何动态加载javascript
【发布时间】:2011-12-18 02:02:08
【问题描述】:

我尝试动态加载一些js文件,例如:

function openInforWindow(){
  //check if the InforWinow.js has been loaded or not
  if(window.InforWindow){
    //do the right thing
  }
  else {
    loadJs('xxxxxx/InforWindow.js');
    // do the right thing
    //but here ,the infowindow is not definded yet.
  }
}

function loadJs(filename){
  var fileref=document.createElement('script')
  fileref.setAttribute("type","text/javascript")
  fileref.setAttribute("src", filename)
  if (typeof fileref!="undefined")
  document.getElementsByTagName("head")[0].appendChild(fileref)
}

如何确保动态加载的js中的变量或函数可以添加到javascript执行环境中以便我可以使用它们?

【问题讨论】:

  • 你在哪里使用参数“文件名”?我猜“js”应该是文件名。在行 fileref.setAttribute("src",filename);
  • 你还是弄错了,即它仍然在双引号内,这使它成为字符串而不是变量。

标签: javascript


【解决方案1】:

添加脚本元素不是阻塞操作,这意味着当您的外部脚本甚至没有加载(也没有解释)时,您的 loadJs 方法会立即返回。您必须等待它加载。

function openInforWindow(){
  //check if the InforWinow.js has been loaded or not
  if(window.InforWindow){
    //do the right thing
  }
  else {
    var loadHandler = function() {
       //do stuff with inforWindow 
    };

    loadJs('xxxxxx/InforWindow.js', loadHandler);

  }
}

function loadJs(filename, handler){
  var fileref=document.createElement('script');
  fileref.setAttribute("type","text/javascript");
  fileref.setAttribute("src", "js");
  fileref.onreadystatechange = function () {
    if (this.readyState == 'complete')handler();
  };
  fileref.onload = handler;
  if (typeof fileref!="undefined")
  document.getElementsByTagName("head")[0].appendChild(fileref);
}

【讨论】:

    【解决方案2】:

    一种方法是使用 jQuery 的 AJAX 加载器加载脚本。示例如下:

    function loadJs(filename, functionToCall){
       $.getScript(filename, functionToCall);
    }
    

    现在,你只需要调用loadJs("script.js", callback);,它会先完全加载script.js,然后运行callback()。

    【讨论】:

    • 当然,在这个例子中你并不真的需要 loadJs 包装器。仅使用 $.getScript() 函数即可实现等效功能。
    【解决方案3】:

    您可以在文档中动态插入<script/> 标签,这是一个可以在 Firefox/chrome 中运行的脚本,您可能需要在 IE 中进行一些调整:

    loadJs = function(src) {
      var script = document.createElement('SCRIPT');
      script.setAttribute('src', src);
      document.getElementsByTagName('HEAD')[0].appendChild(script);
    }
    

    然后等待document.onload 事件触发,您的window.InforWindow 应该在那个阶段加载。

    document.addEventListener('load', function () {
       // Your logic that uses window.InforWindow goes here
    }, false);
    

    请注意,IE 的加载事件侦听器略有不同:

    document.attachEvent('onload', function() {
       // Your logic that uses window.InforWindow goes here
    });
    

    【讨论】:

      猜你喜欢
      • 2010-10-19
      • 1970-01-01
      • 2018-10-11
      • 2012-12-01
      • 1970-01-01
      • 2011-08-15
      • 2011-07-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多