本文表述了關(guān)于js動態(tài)引入四種方式的實例代碼。分享給大家供大家參考,具體如下:
index.html
<html> <head> <meta content="text/html;charset=utf-8" http-equiv="content-type"> <title> </title> <script src='' id="s1"></script> <script src="dynamic.js"></script> </head> <body> </body> </html>
test.js
alert("hello! I am test.js"); var str="1";
dynamic.js
//第一種方式:直接document.write 但這樣會把當(dāng)前的頁面全覆寫掉 //document.write("<script src='test.js'><\/script>"); //第二種方式:動態(tài)改變已有script的src屬性 //s1.src="test.js" //第三種方式:動態(tài)創(chuàng)建script元素 /* var oHead = document.getElementsByTagName('HEAD').item(0); var oScript= document.createElement("script"); oScript.type = "text/javascript"; oScript.src="test.js"; oHead.appendChild(oScript); */ //其實原理就是利用dom動態(tài)的引入一個js到文件中來~就能和原有的js通信了~ //alert(str); /*以上三種方式都采用異步加載機制,也就是加載過程中,頁面會往下走, 如果這樣的話會有問題的,如上面的str就訪問不到,因為當(dāng)程序執(zhí)行alert(str)時,test.js還在加載Ing.... 那么第四種就是基于ajax請求的,且是推薦 */ 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) { includeJS( sId, url, oXmlHttp.responseText ); } } oXmlHttp.open('GET', url, false);//同步操作 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.type = "text/javascript"; oScript.id = sId; oScript.text = source; oHead.appendChild( oScript ); } } ajaxPage( "scrA", "test.js" ); alert( "主頁面動態(tài)加載JS腳本。"); alert( "主頁面動態(tài)加載a.js并取其中的變量:" + str );
上文所表述的全部內(nèi)容是js動態(tài)引入,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com