Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.
     // ...
 });
like image 655
Jan Aagaard Avatar asked Nov 16 '12 09:11

Jan Aagaard


1 Answers

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
 });
like image 85
Robert Hoffmann Avatar answered Oct 19 '22 06:10

Robert Hoffmann