Is it possible to make Head JS's ready() function wait for two scripts?

自闭症网瘾萝莉.ら 提交于 2019-12-10 02:56:35

问题


I load three scripts on my webpage, and I would like to trigger a function once two of them has finished loading.

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

Ideally I would like to be able to do the following, but it does not seem possible to make head.ready() wait for two scripts to load, according to the documentation (see Script Organization).

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

So how should I solve this? If I nest the ready methods, can I be sure that my code will be triggered, or will it only be triggered if jquery finishes loading before analytics?

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

Another solution could be to break up the loading statements into two parts, like this. But will I still benefit fully from the asynchroneous loading of the scripts, or will it finish loading webfont before jquery and analytics?

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

回答1:


Since scripts are executed in order (even though loaded in parallel), you can wait for the script that was "last-in-line"

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


来源:https://stackoverflow.com/questions/13413749/is-it-possible-to-make-head-jss-ready-function-wait-for-two-scripts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!