加载js文件和其他相关的JS文件异步 [英] loading js files and other dependent js files asynchronously

查看:193
本文介绍了加载js文件和其他相关的JS文件异步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在找一个干净的方式异步加载以下类型的JavaScript文件:一个核心的js文件(嗯,我们只是把它,哦,我不知道,哈哈jQuery的!),X Y的依赖于核心js文件被加载js文件数目,以及其他一些不相关的JS文件。我有一个如何去做一对夫妇的想法,但不知道最好的办法是什么。我想,以避免在文档正文加载脚本。

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个JavaScript文件加载异步方式,适当命名的:

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

但是,这是行不通的,因为它不能保证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);
    }
})();

它是pretty太多无法加载jQuery和颜色插件异步? (由于颜色插件需要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源色彩插件脚本到一个文件中。

The first method I was considering is to just combine the color plugin script with jQuery source into one file.

然后另一个想法我已经被加载插件的颜色像这样:

Then another idea I had was loading the color plugin like so:


$(window).ready(function() {
    $.getScript("/js/jquery.color.js");
});

任何人有你如何去什么想法?谢谢!

Anyone have any thoughts on how you'd go about this? Thanks!

推荐答案

LABjs 是专门针对这个问题的。

LABjs is made specifically for this problem.

<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>

您也可以把无关的脚本到自己的 $ LAB 链,如果他们真的没有需要等待jQuery和其它脚本。

You could also put the unrelated scripts into their own $LAB chain, if they really have no need to wait for jQuery and your other scripts.

这篇关于加载js文件和其他相关的JS文件异步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆