Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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.

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

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

  }
}

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

Solution 2:

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

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

Solution 3:

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

Post a Comment for "How To Load Javascript Dynamically"