理解Javascript檔案動態載入_javascript技巧

來源:互聯網
上載者:User

Javascript檔案動態載入一直是比較困擾的一件事情,像網路上傳的比較常見的做法:

function loadjs(fileurl){ var sct = document.createElement("script"); sct.src = fileurl; document.head.appendChild(sct);}

然後我們來測試一下結果:

<html>  <head>   <link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" media="screen" />  </head>  <body>    <script>    function loadjs(fileurl){           var sct = document.createElement("script");     sct.src = fileurl;     document.head.appendChild(sct);    }    loadjs("http://code.jquery.com/jquery-1.12.0.js");    loadjs("http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js")        loadjs("http://bootboxjs.com/bootbox.js")    </script>  </body></html>

代碼載入完後,會出現下圖的錯誤:

jquery明明是載入在第一個處理,為什麼還是報jQuery不存在的對象呢?

因為這樣載入,相當於開啟了三個線程,只是jquery這個檔案先啟動線程,而jquery執行完這個線程的時間,超過了後面兩個時間. 因此後面執行完的,可能沒能找到jquery這個對象。

然這種方式怎麼處理呢?

其實檔案的載入是有個狀態處理的.檔案的載入有個onload事件,就是可以監聽檔案是否載入完成的事件.

因此我們可以考慮這個方法來處理我們想要的結果.我們用直觀的方式來處理.改進後的代碼如下:

 <html>  <head>   <link rel="stylesheet" type="text/css" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" media="screen" />  </head>  <body>    <script>        function loadjs(fileurl, fn){           var sct = document.createElement("script");     sct.src = fileurl;     if(fn){      sct.onload = fn;     }     document.head.appendChild(sct);    }    loadjs("http://code.jquery.com/jquery-1.12.0.js",function(){     loadjs("http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js",function(){        loadjs("http://bootboxjs.com/bootbox.js")     })    });              </script>  </body></html>

OK,執行完這個代碼之後,負載檔案都是在前一個載入完成後,才會載入另外一個,這樣就不會造成找不到用到的對象了.

然後我們來執行一個彈出框的效果,代碼裡面使用了 Bootbox.js 外掛程式. 載入代碼如下:

loadjs("http://code.jquery.com/jquery-1.12.0.js",function(){  loadjs("http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js",function(){       loadjs("http://bootboxjs.com/bootbox.js",function(){          bootbox.alert("Hello world!", function() {           Example.show("Hello world callback");          });       })   }) });

重新整理頁面,就會直接顯示彈出框:

動態載入的代碼,往往容易在這裡花費很多時間調試.大家最好的辦法就是寫一個最簡單的例子,理解其中的原因. 這裡的代碼都可以進行封裝,還可以加入CSS檔案的載入.作為自己的外掛程式使用。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.