是否可以让 Head JS 的 ready() 函数等待两个脚本?



我在网页上加载了三个脚本,我想在其中两个脚本加载完成后触发一个函数。

head.js(
{ webfont: 'http://ajax.googleapis.com/ajax/libs/webfont/1.0.31/webfont.js' },
{ jquery: 'http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js' },
{ analytics: 'http://www.google-analytics.com/ga.js' }
);

理想情况下,我希望能够执行以下操作,但根据文档(请参阅脚本组织),似乎不可能让head.ready()等待两个脚本加载。

head.ready('jquery', function() {
// Code that requires jQuery.
});
// This is not supported. :-(
head.ready('jquery', 'analytics', function() {
// Code that requires both jQuery and Google Analytics.
// ...
});

那么我该如何解决这个问题呢?如果我嵌套ready方法,我能确定我的代码会被触发吗?还是只有当jquery在分析之前完成加载时才会被触发?

head.ready('jquery', function() {
// Code that requires jQuery.
// ...
head.ready('analytics', function() {
// Code that requires both jQuery and Google Analytics.
// ...
});
});

另一种解决方案可能是将加载语句分解为两部分,如下所示。但是,我仍然会从脚本的异步加载中完全受益吗?还是会在jquery和analytics之前完成webfont的加载?

head.js(
{ webfont: 'http://ajax.googleapis.com/ajax/libs/webfont/1.0.31/webfont.js' }
);
head.js(
{ jquery: 'http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js' },
{ analytics: 'http://www.google-analytics.com/ga.js' },
function() {
// Code that requires both jQuery and Google Analytics.
// ...
}
);
head.ready('jquery', function() {
// Code that requires jQuery.
// ...
});

由于脚本是按顺序执行的(即使是并行加载的),您可以等待中"最后一行"的脚本

head.js(
{ webfont  : 'http://ajax.googleapis.com/ajax/libs/webfont/1.0.31/webfont.js' },
{ jquery   : 'http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js' },
{ analytics: 'http://www.google-analytics.com/ga.js' }
);
head.ready('analytics', function() {
// when this triggers, webfont & jquery will have finished loading too
});

最新更新