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

loading js files and other dependent js files asynchronously(异步加载js文件和其他依赖的js文件)

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

问题描述

我正在寻找一种干净的方式来异步加载以下类型的 javascript 文件:核心"js 文件(嗯,我们就这样称呼它吧,哦,我不知道,jquery!"哈哈),x依赖于正在加载的核心" js 文件的 js 文件数量,以及 y 个其他不相关的 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);
    }
})();

几乎不可能异步加载 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 和 RequireJS 是目前两个流行的选择.它们都适用于 jQuery,但采用的方法略有不同,因此您应该同时查看两者.

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.

这篇关于异步加载js文件和其他依赖的js文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:异步加载js文件和其他依赖的js文件

基础教程推荐