html中動態加載
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>");