异步加载js文件和其他依赖的js文件

tab*_*ber 14 javascript jquery asynchronous jquery-plugins labjs

我正在寻找一种干净的方式来异步加载以下类型的javascript文件:一个"核心"js文件(嗯,我只是叫它,哦,我不知道,"jquery!"哈哈),x个js依赖于正在加载的"核心"js文件的文件,以及y个其他不相关的js文件.我有几个关于如何去做的想法,但不知道最好的方法是什么.我想避免在文档正文中加载脚本.

因此,例如,我希望以下4个javascript文件异步加载,适当命名:


/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
Run Code Online (Sandbox Code Playgroud)

但这不起作用,因为它不能保证在颜色插件之前加载jQuery ...


(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);
    }
})();
Run Code Online (Sandbox Code Playgroud)

几乎不可能异步加载jquery和颜色插件?(因为颜色插件需要首先加载jQuery.)

我考虑的第一种方法是将颜色插件脚本和jQuery源组合到一个文件中.

然后我的另一个想法是加载颜色插件,如下所示:


$(window).ready(function() {
    $.getScript("/js/jquery.color.js");
});
Run Code Online (Sandbox Code Playgroud)

任何人都对你如何做到这一点有任何想法?谢谢!

bch*_*rry 12

LABjs专门针对这个问题而制作.

<script src="lab.js"></script>
<script>
  $LAB
    .script("jquery.js")
    .wait()
    .script("jquery.color.js")
    .script("jquery.otherplugin.js")
    .script("mylib.js")
    .wait()
    .script("unrelated1.js")
    .script("unrelated2.js");
</script>
Run Code Online (Sandbox Code Playgroud)

$LAB如果他们真的不需要等待jQuery和其他脚本,你也可以将不相关的脚本放入他们自己的链中.


ndp*_*ndp 5

LabJSRequireJS是目前两种流行的选择.他们都使用jQuery但采用略有不同的方法,所以你应该看看两者.