js非同步動態載入js與css檔案代碼

來源:互聯網
上載者:User

jquery動態載入css,js檔案方法簡單很,

方法1:

 代碼如下 複製代碼
$.getscript("test.js");

方法2:

 代碼如下 複製代碼

function loadjs(file){  

     var head = $('head').remove('#loadscript'); 

    $("<scri"+"pt>"+"</scr"+"ipt>").attr({src:file,type:'text/javascript',id:'load'}).appendto(head); 

}

方法3:

 代碼如下 複製代碼

$("<scri"+"pt>"+"</scr"+"ipt>").attr({src:file,type:'text/javascript',id:'load'}).appendto($('head').remove('#loadscript'));

下面附一些js動態載入js,css檔案的方法。

以下代碼是摘自news.qq.com頁面裡的代碼的,本人未進行測試,程式看著應該沒有問題的,可以做為參考的,主要用來在網頁底部位置,實現動態載入js檔案到網頁<head>標籤的後面,通過DOM來實現的,代碼如下:

 代碼如下 複製代碼

<script>
 var SCRIPT_TIMEOUT = 20000;
 var QVPL_PATH = "/QVPL1.0.0.js";
 
 function loadHelper (jsurl) {
 var oScriptEl, oTimeoutHDL, oHead;
 oScriptEl = document.createElement("script");
 oScriptEl.type = "text/javascript";
 oScriptEl.language = "javascript";
 oScriptEl.src = jsurl;
 oScriptEl.onreadystatechange = doCallback;
 
 oScriptEl.onload = function()
 {
 this.readyState = "complete";
 doCallback();
 if(typeof(lianbo) == "object"){
 lianbo.init(window.QVPL);
 }
 };
 
 oTimeoutHDL = window.setTimeout(doError,SCRIPT_TIMEOUT);
 document.getElementsByTagName("head")[0].appendChild(oScriptEl);
 
 function doCallback()
 {
 if (oScriptEl.readyState == "complete" || oScriptEl.readyState == "loaded")
 {
 oScriptEl.onload = oScriptEl.onreadystatechange = new Function();
 window.clearTimeout(oTimeoutHDL);
 }
 };
 
 function doError()
 {
 oScriptEl.parentNode.removeChild(oScriptEl);
 };
 }
 
 loadHelper(QVPL_PATH);
 </script>

相關文章

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.