同步非同步動態引入js檔案的幾種方法

來源:互聯網
上載者:User

動態載入js檔案
有時候我們需要根據參數不同來引入不同的js檔案,用html直接寫標籤滿足不了我們的需求,總結幾種方法,以及同步非同步載入的各種需求
一.直接載入
<div id="divId"></div>
<script>
一.非同步載入,並發執行,但引入js內容不能直接使用
  //1.1 直接document.write
     document.write("<script src='test.js'><\/script>"); 
   //1.2 動態改變已有script的src屬性
    //頁面中有<script src='' id="s1"></ script> 
document.getElementById('s1').src="test.js";
     //1.3 動態建立js
     var rootObject=document.getElementById("divId");
     var oScript = document.createElement( "script" );
     oScript.type = "text/javascript"; 
     oScript.src = test.js; //test.js方法中有一個方法function test(){alert("test");}
     rootObject.appendChild(oScript); 
     //2.0 調用js
     test();//在ie中不會出錯,在firefox會出錯,因為firefox預設為非同步載入(在向伺服器請求載入test.js檔案的同時,繼續向下執行了,調用test()方法,就自然找不到這個方法)
二.同步載入,單步載入,引入js內容可以直接使用
var Skip={};
//擷取XMLHttpRequest對象(提供用戶端同http伺服器通訊的協議)
Skip.getXmlHttpRequest=function (){ 
    if ( window.XMLHttpRequest ) // 除了IE外的其它瀏覽器
           return new XMLHttpRequest() ; 
    else if ( window.ActiveXObject ) // IE 
            return new ActiveXObject("MsXml2.XmlHttp") ; 
},
//匯入內容
Skip.includeJsText =function (rootObject,jsText){ 
        if ( rootObject != null ){ 
             var oScript = document.createElement( "script" );
             oScript.type = "text/javascript"; 
            //oScript.id = sId; 
            //oScript.src = fileUrl; 
            //oScript.defer = true; 
            oScript.text = jsText; 
            rootObject.appendChild(oScript); 
            //alert(oScript.text);
        } 
       },
//匯入檔案
Skip.includeJsSrc =function (rootObject, fileUrl){ 
        if ( rootObject != null ){ 
             var oScript = document.createElement( "script" ); 
             oScript.type = "text/javascript"; 
             oScript.src = fileUrl; 
             rootObject.appendChild(oScript); 
       } 
      },
//同步載入
Skip.addJs=function(rootObject, url){ 
        var oXmlHttp = Skip.getXmlHttpRequest() ; 
        oXmlHttp.onreadystatechange = function(){//其實當在第二次調用匯入js時,因為在瀏覽器當中存在這個*.js檔案了,它就不在訪問伺服器,也就不在執行這個方法了,這個方法也只有設定成非同步時才用到
            if ( oXmlHttp.readyState == 4 ){ //當執行完成以後(返回了響應)所要執行的
                if ( oXmlHttp.status == 200 || oXmlHttp.status == 304 ){ //200有讀取對應的url檔案,404表示不存在這個檔案
                   Skip.includeJsSrc( rootObject, url); 
                }  else{ 
                    alert( 'XML request error: ' + oXmlHttp.statusText + ' (' + oXmlHttp.status + ')' ) ; 
                } 
            } 
         } 
         //1.True 表示指令碼會在 send() 方法之後繼續執行,而不等待來自伺服器的響應,並且在open()方法當中有調用到onreadystatechange()這個方法。通過把該參數設定為 "false",可以省去額外的 onreadystatechange 代碼,它表示伺服器返迴響應後才執行send()後面的方法.
         //2.同步執行oXmlHttp.send()方法後oXmlHttp.responseText有返回對應的內容,而非同步還是為空白,只有在oXmlHttp.readyState == 4時才有內容,反正同步的在oXmlHttp.send()後的操作就相當於oXmlHttp.readyState == 4下的操作,它相當於只有了這一種狀態.
      oXmlHttp.open('GET', url, false); //url為js檔案時,ie會自動產生 '<script src="*.js" type="text/javascript"> </scr ipt>',ff不會  
      oXmlHttp.send(null); 
      Skip.includeJsText(rootObject,oXmlHttp.responseText);
      }
};
var rootObject=document.getElementById("divId");
Skip.addJs(rootObject,"test.js")//test.js檔案中含有funciotn test(){alert("test");}
test();//即使馬上調用也不會出錯了.
</script>
總結:
1.ie動態載入js檔案時,它預設就為同步,可以不用設定同步(也可直調用Skip.includeJsSrc())
2.ff動態載入js檔案時,它預設為非同步,要設定成同步,載入完直接調用才不會出錯
3.無論ie還是ff在動態載入js內容時,沒有請求伺服器,不會存在非同步問題
注:無論ie還是ff在頁面載入js時(即執行整個頁面),都是為同步的載入,除非設定script的屬性defer="true"(此屬性好像也只是對ie有效)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.