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
- // you need to put an escape character before the closing </script> tag, like this: </script>
- <script language=”javascript”>
- document.write(“<script src=’other.js’></script>”);
- </script>
choice 2.Dynamically change the src property value
- <script src=” id=”s1″></script>
- <script language=”javascript”>
- s1.src=”other.js”
- </script>
choice 3.Dynamically create <script> element
- <script>
- var oHead = document.getElementsByTagName(‘HEAD’).item(0);
- var oScript= document.createElement(“script”);
- oScript.type = “text/javascript”;
- oScript.src=”other.js”;
- oHead.appendChild( oScript);
- </script>
choice 4. Get JavaScript by using XMLHTTP,then create script object
- <script language=”JavaScript”>
- function GetHttpRequest()
- {
- if ( window.XMLHttpRequest ) // Gecko
- return new XMLHttpRequest() ;
- else if ( window.ActiveXObject ) // IE
- return new ActiveXObject(“MsXml2.XmlHttp”) ;
- }
- function AjaxPage(sId, url){
- var oXmlHttp = GetHttpRequest() ;
- oXmlHttp.OnReadyStateChange = function()
- {
- if ( oXmlHttp.readyState == 4 )
- {
- if ( oXmlHttp.status == 200