javascript
动态加载JS脚本的4种方法
| 要實(shí)現(xiàn)動(dòng)態(tài)加載JS腳本有4種方法: ????document.write("<script?src='test.js'><//script>"); </script> ? 2、動(dòng)態(tài)改變已有script的src屬性 <script?src=''?id="s1"></script><script?language="javascript"> ????s1.src="test.js" </script> ? 3、動(dòng)態(tài)創(chuàng)建script元素 <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> ? 這三種方法都是異步執(zhí)行的,也就是說(shuō),在加載這些腳本的同時(shí),主頁(yè)面的腳本繼續(xù)運(yùn)行,如果用以上的方法,那下面的代碼將得不到預(yù)期的效果。 要?jiǎng)討B(tài)加載的JS腳本:a.js,以下是該文件的內(nèi)容。 var?str?=?"中國(guó)";alert(?"這是a.js中的變量:"?+?str?); ?
<script?language="JavaScript"> function?LoadJS(?id,?fileUrl?) { ?? ?var?scriptTag?=?document.getElementById(?id?);? ????var?oHead?=?document.getElementsByTagName('HEAD').item(0); ?? ?var?oScript=?document.createElement("script"); ?? ?if?(?scriptTag??)?oHead.removeChild(?scriptTag??);? ????oScript.id?=?id;? ??? oScript.type?=?"text/javascript";? ????oScript.src=fileUrl?;? ??? oHead.appendChild(?oScript);? } LoadJS(?"a.js"?); alert(?"主頁(yè)面動(dòng)態(tài)加載a.js并取其中的變量:"?+?str?); </script> 上述代碼執(zhí)行后 a.js 的 alert 執(zhí)行并彈出消息, 4、原理:用XMLHTTP取得要腳本的內(nèi)容,再創(chuàng)建 Script 對(duì)象。 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(?"主頁(yè)面動(dòng)態(tài)加載JS腳本。"); alert(?"主頁(yè)面動(dòng)態(tài)加載a.js并取其中的變量:"?+?str?); </script> 現(xiàn)在完成了一個(gè)JS腳本的動(dòng)態(tài)加載。 var?Rash=true; |
總結(jié)
以上是生活随笔為你收集整理的动态加载JS脚本的4种方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 获奖者:郑纬民,男,清华大学教授、博士
- 下一篇: 【计算机组成原理】虚拟存储器和Cache