-->

是否有可能使头JS的ready()函数等待两个脚本?(Is it possible to make

2019-08-02 19:57发布

我在我的网页加载三个脚本,我想一旦他们两个已经完成加载触发功能。

 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.
    // ...
});

所以,我应该怎么解决这个问题? 如果我巢准备好方法,我可以肯定,我的代码将被触发,还是会如jQuery的完成分析之前只加载被触发?

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

另一种解决方案可能是装载语句分解成两个部分,像这样。 但我仍会从脚本的asynchroneous加载中充分受益,还是会jQuery和分析之前完成加载web字体?

 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.
     // ...
 });

Answer 1:

因为脚本是为了(即使装在并行)执行的,你可以等待,这是“最后在线”的剧本

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
 });


文章来源: Is it possible to make Head JS's ready() function wait for two scripts?