如何动态加载javascript

如何动态加载javascript,javascript,Javascript,我尝试动态加载一些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 inf

我尝试动态加载一些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执行环境中,以便我可以使用它们?

您可以在文档中动态插入
标记,下面是一个在firefox/chrome中工作的脚本,您可能需要在IE中进行一些调整:

loadJs = function(src) {
  var script = document.createElement('SCRIPT');
  script.setAttribute('src', src);
  document.getElementsByTagName('HEAD')[0].appendChild(script);
}
然后等待
document.onload
事件触发,此时应加载
窗口.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
});

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

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

现在,您只需要调用
loadJs(“script.js”,callback),它将首先完全加载script.js,然后运行callback()。

添加脚本元素不是阻塞操作,这意味着当外部脚本甚至没有加载(或解释)时,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);
}

当然,在本例中,您并不真正需要loadJs包装器。只有使用$.getScript()函数才能实现等效的功能。您在哪里使用参数“filename”?我想“js”应该是文件名。在fileref.setAttribute行中(“src”,filename);你还是弄错了(它仍然在双引号内,这使它成为字符串而不是变量)。