hguser
hguser

Reputation: 36028

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 ?

Upvotes: 0

Views: 1638

Answers (3)

Steven de Salas
Steven de Salas

Reputation: 21467

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

Upvotes: 0

Roman
Roman

Reputation: 6428

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

Upvotes: 1

Isaac Lewis
Isaac Lewis

Reputation: 1199

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().

Upvotes: 0

Related Questions