How to load javascript dynamically

I am trying 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 vars or functions in js that are dynamically loaded can be added to the javascript runtime so that I can use them?

0
source share
3 answers

Adding a script element is not a lock, this means that your loadJs method returns immediately when your external script is not loaded (and not interpreted). You must 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);
}
+1
source

You can dynamically insert a tag <script/>into your document, here is a script that will work in firefox / chrome, you may need a little tweaking in 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
});
0

One approach would be to load the script using the jQuery 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 load script.js completely, and then run the callback ().

0
source