4 ways to dynamically load external JavaScript(with source)

 

Most of the time, Firefox, Safari and Opera work without much effort and differences between the 3. However, throw IE into the mix and you’re in a whole different world.This is helpful if you need to dynamically inject javascript.And, the biggest problem was setting a function that you want executed after the script is loaded.By this article I will provide 4 way to dynamically load external JavaScript.

The below 1,2,3 are asynchronous,only 4 is synchronization.

 

choice 1. Using document.write

  1. // you need to put an escape character before the closing </script> tag, like this: </script>
  2. <script language=”javascript”>
  3. document.write(“<script src=’other.js’></script>”);
  4. </script>

choice 2.Dynamically change the src property value

  1. <script src=” id=”s1″></script>
  2. <script language=”javascript”>
  3. s1.src=”other.js”
  4. </script>

choice 3.Dynamically create <script> element

  1. <script>
  2. var oHead = document.getElementsByTagName(‘HEAD’).item(0);
  3. var oScript= document.createElement(“script”);
  4. oScript.type = “text/javascript”;
  5. oScript.src=”other.js”;
  6. oHead.appendChild( oScript);
  7. </script>

choice 4. Get JavaScript by using XMLHTTP,then create script object

  1. <script language=”JavaScript”>
  2. function GetHttpRequest()
  3. {
  4. if ( window.XMLHttpRequest ) // Gecko
  5. return new XMLHttpRequest() ;
  6. else if ( window.ActiveXObject ) // IE
  7. return new ActiveXObject(“MsXml2.XmlHttp”) ;
  8. }
  9. function AjaxPage(sId, url){
  10. var oXmlHttp = GetHttpRequest() ;
  11. oXmlHttp.OnReadyStateChange = function()
  12. {
  13. if ( oXmlHttp.readyState == 4 )
  14. {
  15. if ( oXmlHttp.status == 200