js動態引入的四種方式


index.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<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.... 
 
<strong><span style="color:#ff0000;">那么第四種就是基於ajax請求的,且是推薦</span></strong> 
*/  
  
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 );  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM