問(wèn)題描述
我正在尋找一種干凈的方式來(lái)異步加載以下類型的 javascript 文件:核心"js 文件(嗯,我們就這樣稱呼它吧,哦,我不知道,jquery!"哈哈),x依賴于正在加載的核心" js 文件的 js 文件數(shù)量,以及 y 個(gè)其他不相關(guān)的 js 文件.我有一些關(guān)于如何去做的想法,但不確定最好的方法是什么.我想避免在文檔正文中加載腳本.
I'm looking for a clean way to asynchronously load the following types of javascript files: a "core" js file (hmm, let's just call it, oh i don't know, "jquery!" haha), x number of js files that are dependent on the "core" js file being loaded, and y number of other unrelated js files. I have a couple ideas of how to go about it, but not sure what the best way is. I'd like to avoid loading scripts in the document body.
例如,我希望以下 4 個(gè) javascript 文件異步加載,并適當(dāng)命名:
So for example, I want the following 4 javascript files to load asynchronously, appropriately named:
/js/my-contact-page-js-functions.js // unrelated/independent script
/js/jquery-1.3.2.min.js // the "core" script
/js/jquery.color.min.js // dependent on jquery being loaded
http://thirdparty.com/js/third-party-tracking-script.js // another unrelated/independent script
但這行不通,因?yàn)椴荒鼙WC jQuery 在顏色插件之前加載...
But this won't work because it's not guaranteed that jQuery is loaded before the color plugin...
(function() {
var a=[
'/js/my-contact-page-functions.js',
'/js/jquery-1.4.2.min.js',
'/js/jquery.color.js',
'http://cdn.thirdparty.com/third-party-tracking-script.js',
],
d=document,
h=d.getElementsByTagName('head')[0],
s,
i,
l=a.length;
for(i=0;i<l;i++){
s=d.createElement('script');
s.type='text/javascript';
s.async=true;
s.src=a[i];
h.appendChild(s);
}
})();
幾乎不可能異步加載 jquery 和顏色插件嗎?(因?yàn)轭伾寮笙燃虞d jQuery.)
Is it pretty much not possible to load jquery and the color plugin asynchronously? (Since the color plugin requires that jQuery is loaded first.)
我考慮的第一種方法是將顏色插件腳本與 jQuery 源合并到一個(gè)文件中.
The first method I was considering is to just combine the color plugin script with jQuery source into one file.
然后我的另一個(gè)想法是像這樣加載顏色插件:
Then another idea I had was loading the color plugin like so:
$(window).ready(function() {
$.getScript("/js/jquery.color.js");
});
有人對(duì)你將如何處理這件事有任何想法嗎?謝謝!
Anyone have any thoughts on how you'd go about this? Thanks!
推薦答案
LabJS 和 RequireJS 是目前兩個(gè)流行的選擇.它們都適用于 jQuery,但采用的方法略有不同,因此您應(yīng)該同時(shí)查看兩者.
LabJS and RequireJS are two popular choices right now. They both work with jQuery but take slightly different approaches, so you should look at both.
這篇關(guān)于異步加載js文件和其他依賴的js文件的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!