本文表述了關于js動態引入四種方式的實例代碼。分享給大家供大家參考,具體如下:
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 但這樣會把當前的頁面全覆寫掉 //document.write("<script src='test.js'><//script>");  //第二種方式:動態改變已有script的src屬性 //s1.src="test.js"  //第三種方式:動態創建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動態的引入一個js到文件中來~就能和原有的js通信了~ //alert(str);  /*以上三種方式都采用異步加載機制,也就是加載過程中,頁面會往下走, 如果這樣的話會有問題的,如上面的str就訪問不到,因為當程序執行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( "主頁面動態加載JS腳本。"); alert( "主頁面動態加載a.js并取其中的變量:" + str ); 上文所表述的全部內容是js動態引入,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對VeVb武林網的支持。
新聞熱點
疑難解答