讓JavaScript和其它資源并發(fā)下載的方法
在IE6/7里JavaScript會從兩個方面阻礙頁面呈現(xiàn):
script標(biāo)簽下面的網(wǎng)頁資源在script加載完之前會停止請求、下載。
script標(biāo)簽下面的html元素在script加載完之前會停止渲染。
在ie6/7 firefox2/3 Safari3 Chrome1 和 opera下 script標(biāo)簽會阻礙下載:

雖然在ie8,safari4,chrome2下script可以并發(fā),但依然阻礙了其他資源的下載:

有6種方法可以使script與其他資源并行下載:
1.XHR eval — 通過XHR(XMLHttpRequest 對象)下載script,然后用eval方法執(zhí)行XHR的responseText
2.XHR Injection — 通過XHR下載script,然后建立一個script標(biāo)簽并把它插入文檔中(body或者h(yuǎn)ead標(biāo)簽內(nèi)),接著把script標(biāo)簽的text屬性設(shè)置為XHR的responseText的值
3.XHR in Iframe — 把script標(biāo)簽放到一個iframe里,通過iframe下載它
4.Script DOM Element — 創(chuàng)建script標(biāo)簽并把它的src屬性指向你的腳本地址
5.Script Defer — 添加script標(biāo)簽的defer屬性,這個只在ie中有效,但firefox3.1也支持這個屬性了
6.使用document.write方法在頁面中寫入<script src="">,這個只在ie里有效
可以通過Cuzillion查 看各個方法的使用例子。
如果有一些內(nèi)聯(lián)腳本需要在外部腳本執(zhí)行后才能執(zhí)行,那就需要同步(synchronize)他們了。稱作”coupling”,Coupling Asynchronous Scripts 這篇文章介紹了一些目前可以實現(xiàn)“coupling”的方法。
headjs,能使JS并發(fā)下載(但是順序執(zhí)行):http://headjs.com/
head.js("/path/to/jquery.js", "/google/analytics.js", "/js/site.js", function() {
// all done
});
// the most simple case. load and execute single script without blocking.
head.js("/path/to/file.js");
// load a script and execute a function after it has been loaded
head.js("/path/to/file.js", function() {
});
// load files in parallel but execute them in sequence
head.js("file1.js", "file2.js", ... "fileN.js");
// execute function after all scripts have been loaded
head.js("file1.js", "file2.js", function() {
});
// files are loaded in parallel and executed in order they arrive
head.js("file1.js");
head.js("file2.js");
head.js("file3.js");
// the previous can also be written as
head.js("file1.js").js("file1.js").js("file3.js");
相關(guān)文章
Javascript 鼠標(biāo)移動上去小三角形滑塊緩慢跟隨效果
一個tab選項卡,當(dāng)鼠標(biāo)移動上去時紅色滑塊跟隨,在布局過程中經(jīng)常會使用到,本文提供了詳細(xì)的實現(xiàn)代碼,感興趣的朋友可以參考下2013-04-04
layui文件上傳控件帶更改后數(shù)據(jù)傳值的方法
今天小編就為大家分享一篇layui文件上傳控件帶更改后數(shù)據(jù)傳值的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-09-09
Layui實現(xiàn)數(shù)據(jù)表格中鼠標(biāo)懸浮圖片放大效果,離開時恢復(fù)原圖的方法
今天小編就為大家分享一篇Layui實現(xiàn)數(shù)據(jù)表格中鼠標(biāo)懸浮圖片放大效果,離開時恢復(fù)原圖的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-09-09

