Created
December 8, 2014 01:56
-
-
Save bytezen/844f1a8cd11590dded57 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// from http://ntt.cc/2008/02/10/4-ways-to-dynamically-load-external-javascriptwith-source.html | |
// TODO: will make mddn242 specific examples | |
// you need to put an escape character before the closing </script> tag, like this: <\/script> | |
1. use document write | |
<script language="javascript"> | |
document.write("<script src='other.js'><\/script>"); | |
</script> | |
2. Dynamically change the src attribute | |
<script src='' id="s1"></script> | |
<script language="javascript"> | |
s1.src="other.js" | |
</script> | |
3. Dynamically create a 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> | |
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 || oXmlHttp.status == 304 ) | |
{ | |
IncludeJS( sId, url, oXmlHttp.responseText ); | |
} | |
else | |
{ | |
alert( 'XML request error: ' + oXmlHttp.statusText + ' (' + oXmlHttp.status + ')' ) ; | |
} | |
} | |
} | |
oXmlHttp.open('GET', url, true); | |
oXmlHttp.send(null); | |
} | |
function IncludeJS(sId, fileUrl, source) | |
{ | |
if ( ( source != null ) && ( !document.getElementById( sId ) ) ){ | |
var oHead = document.getElementsByTagName('HEAD').item(0); | |
var oScript = document.createElement( "script" ); | |
oScript.language = "javascript"; | |
oScript.type = "text/javascript"; | |
oScript.id = sId; | |
oScript.defer = true; | |
oScript.text = source; | |
oHead.appendChild( oScript ); | |
} | |
} | |
AjaxPage( "scrA", "b.js" ); | |
alert( "dynamically load javascript"); | |
alert( "dynamically load a.js and get the variable:" + str ); | |
</script> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment