動態載入script檔案的兩種方法

來源:互聯網
上載者:User

動態載入script到頁面大約有倆方法

第一種就是利用ajax方式,把script檔案代碼從後台載入到前台,然後對載入到的內容通過eval()執行代碼。第二種是,動態建立一個script標籤,設定其src屬性,通過把script標籤插入到頁面head來載入js,相當於在head中寫了一個<script src="..."></script>,只不過這個script標籤是用js動態建立的
比如說是我們要動態地載入一個callbakc.js,我們就需要這樣一個script標籤:
複製代碼 代碼如下:
<script type="text/javascript" src="call.js"></script>

如下代碼就是如何通過js來建立這個標籤(並且加到head中):
複製代碼 代碼如下:
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.type= 'text/javascript';
script.src= 'call.js';
head.appendChild(script);

當載入完call.js, 我們就要調用其中的方法。不過在header.appendChild(script)之後我們不能馬上調用其中的js。因為瀏覽器是非同步載入這個js的,我們不知道他什麼時候載入完。然而我們可以通過監聽事件的辦法來判斷helper.js是否載入完成。(假設call.js中有一個callback方法)
複製代碼 代碼如下:
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.type= 'text/javascript';
script.onreadystatechange= function () {
if (this.readyState == 'complete')
callback();
}
script.onload= function(){
callback();
}
script.src= 'helper.js';
head.appendChild(script);

我設了2個事件監聽函數, 因為在ie中使用onreadystatechange, 而gecko,webkit 瀏覽器和opera都支援onload。事實上this.readyState == 'complete'並不能工作的很好,理論上狀態的變化是如下步驟:
0 uninitialized
1 loading
2 loaded
3 interactive
4 complete
但是有些狀態會被跳過。根據經驗在ie7中,只能獲得loaded和completed中的一個,不能都出現,原因也許是對判斷是不是從cache中讀取影響了狀態的變化,也可能是其他原因。最好把判斷條件改成this.readyState == 'loaded' || this.readyState == 'complete'

參考jQuery的實現我們最後實現為:
複製代碼 代碼如下:
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.type= 'text/javascript';
script.onload = script.onreadystatechange = function() {
if (!this.readyState || this.readyState === "loaded" || this.readyState === "complete" ) {
help();
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
} };
script.src= 'helper.js';
head.appendChild(script);

還有一種簡單的情況就是可以把help()的調用寫在helper.js的最後,那麼可以保證在helper.js在載入完後能自動調用help(),當然最後還要能這樣是不是適合你的應用。

另外需要注意:

1.因為script標籤的src可以跨域訪問資源,所以這種方法可以類比ajax,解決ajax跨域訪問的問題。
2.如果用ajax返回的html代碼中包含script,則直接用innerHTML插入到dom中是不能使html中的script起作用的。粗略的看了下jQuery().html(html)的原代碼,jQuery也是先解析傳入的參數,剝離其中的script代碼,動態建立script標籤,所用jQuery的html方法添加進dom的html如果包含script是可以執行的。如:
複製代碼 代碼如下:
jQuery("#content").html("<script>alert('aa');<\/script>");

聯繫我們

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