Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Dynamically including JavaScript files

DHTML

Dynamically including JavaScript files

by  adam0101  Posted    (Edited  )
Typical solutions to this problem involve manipulating the DOM to insert a JavaScript include statement. Doing it this way may cause an error if a function from the file is called immediately after including the file because the browser still has to retrieve it from the server. To get past this you can use AJAX to make a synchonous call to the server to get the file contents.
Code:
function include(src)
{
  var js=document.createElement('script');
  js.type='text/javascript';

  [green]// Attempt to create an AJAX object[/green]
  var xmlHttp;
  try{xmlHttp=new XMLHttpRequest();}
  catch(e){
    try{xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");}
    catch(e){
      try{xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");}
      catch(e){
        [green]// Ajax not supported, use DOM instead.[/green]
        js.src=src;document.getElementsByTagName('head')[0].appendChild(js);
      } 
    }
  }

  if(xmlHttp){
    xmlHttp.open("GET",src,false);
    xmlHttp.onreadystatechange=function(){
      if(xmlHttp.readyState==4){
        js.text = xmlHttp.responseText;
        document.getElementsByTagName('head')[0].appendChild(js);
      }
    }
    xmlHttp.send(null);
  }
}
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top