简体   繁体   中英

how to load javascript dynamically

I try to load some js files dynamically,for example:

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)
}

How to make sure that the vars or functions in the js which is dynamically loaded can be add to the javascript execute environment so I can use them ?

adding a script element isn't a blocking operation, this means that your loadJs method returns immediately when your external script isn't even loaded (nor interpreted). You have to wait for it to load.

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);
}

You can dynamically insert a <script/> tag into your document, here is a script that will work in firefox/chrome, you may need a bit of tweaking in IE:

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

Then wait for the document.onload event to fire, your window.InforWindow should be loaded at that stage.

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

Note that IE does the load event listener slightly differently:

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

One approach could be to load the script using jQuery's AJAX loader. Example below:

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

Now, you just need to call loadJs("script.js", callback); , and it will first completely load script.js, and then run callback().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM