我正在寻找一种干净的方法来异步加载以下类型的 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
但这行不通,因为不能保证 jQuery 在颜色插件之前加载...
(function() {
var a=[
'/js/my-contact-page-functions.js',
<b>'/js/jquery-1.4.2.min.js',
'/js/jquery.color.js',</b>
'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。)
我考虑的第一个方法是将颜色插件脚本与 jQuery 源合并到一个文件中。
然后我的另一个想法是像这样加载颜色插件:
$(window).ready(function() {
$.getScript("/js/jquery.color.js");
});
有人对您将如何处理这件事有任何想法吗?谢谢!
最佳答案
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>
如果它们真的不需要等待 jQuery 和您的其他脚本,您也可以将不相关的脚本放入它们自己的 $LAB
链中。
关于javascript - 异步加载js文件和其他依赖的js文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2777030/