Sometimes we need to dynamically add suitable js, because sometimes we don’t need to load all js in order to improve efficiency. The following are 4 commonly used methods
1. Direct document.write
<script language="javascript"> document.write("<script src='test.js'><\/script>"); </script>
2. Dynamically change the src attribute of an existing script
<script src='' id="s1"></script> <script language="javascript"> s1.src="test.js" </script>
3. Dynamically create script element
<script> var oHead = document.getElementsByTagName('HEAD').item(0); var oScript= document.createElement("script"); oScript.type = "text/javascript"; oScript.src="test.js"; oHead.appendChild( oScript); </script>
These three methods are executed asynchronously
4. Principle: Use XMLHTTP to obtain the content of the script , and then create a Script object.
Note: a.js must be saved in UTF8 encoding to avoid errors. Because the server and XML use UTF8 encoding to transmit data.
Main page code:
<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( "主页面动态加载JS脚本。"); alert( "主页面动态加载a.js并取其中的变量:" + str ); </script>
The dynamic loading of a JS script is now completed.
var Rash=true; var msg=""; function norash() { if (confirm("确定要取消吗")) Rash=false; } function rashit() { setInterval('getrss()',Inttime); } function getrss() { if (Rash==true) { head=document.getElementsByTagName('head').item(0); script=document.createElement('script'); script.src='INCLUDE/AutoUpdate.asp'; script.type='text/javascript'; script.defer=true; void(head.appendChild(script)); window.status=msg; } } rashit();
The above is the detailed content of Code summary of four commonly used JavaScript dynamic loading methods. For more information, please follow other related articles on the PHP Chinese website!