@@ -106,6 +106,7 @@ Analytics.prototype.init = Analytics.prototype.initialize = function(settings, o
106
106
107
107
this . _options ( options ) ;
108
108
this . _readied = false ;
109
+ this . _readiedIntegrations = { } ;
109
110
110
111
// clean unknown integrations from settings
111
112
var self = this ;
@@ -146,8 +147,14 @@ Analytics.prototype.init = Analytics.prototype.initialize = function(settings, o
146
147
integration . page = after ( 2 , integration . page ) ;
147
148
}
148
149
150
+ var integrationReady = function ( ) {
151
+ self . _readiedIntegrations [ integration . name ] = true ;
152
+ self . emit ( integration . name + '-ready' ) ;
153
+ ready ( ) ;
154
+ } ;
155
+
149
156
integration . analytics = self ;
150
- integration . once ( 'ready' , ready ) ;
157
+ integration . once ( 'ready' , integrationReady ) ;
151
158
integration . initialize ( ) ;
152
159
} , integrations ) ;
153
160
@@ -496,14 +503,56 @@ Analytics.prototype.alias = function(to, from, options, fn) {
496
503
return this ;
497
504
} ;
498
505
506
+ /**
507
+ * Register a `fn` to be fired when integrations are ready.
508
+ * If the first parameter is a function `fn`, `fn` is firsted when all
509
+ * integrations are ready.
510
+ * If the first parameter is a name and the second parameter is a function `fn`,
511
+ * `fn` is fired when the given integration is ready.
512
+ *
513
+ * It is recommended that you use the latter, as the global ready callback may
514
+ * not be fired if a single integration fails to load.
515
+ * See https://github.com/segmentio/analytics.js/issues/409.
516
+ *
517
+ * @param {(Function|String) } a
518
+ * @param {Function } b
519
+ * @return {Analytics }
520
+ */
521
+
522
+ Analytics . prototype . ready = function ( a , b ) {
523
+ if ( is . fn ( a ) ) {
524
+ return this . _ready ( a ) ;
525
+ }
526
+ return this . _integrationReady ( a , b ) ;
527
+ } ;
528
+
529
+ /**
530
+ * Register a `fn` to be fired when the given analytics service is ready.
531
+ *
532
+ * @param {Function } fn
533
+ * @return {Analytics }
534
+ */
535
+
536
+ Analytics . prototype . _integrationReady = function ( name , fn ) {
537
+ if ( is . fn ( fn ) ) {
538
+ var integrations = this . _readiedIntegrations || { } ;
539
+ if ( integrations [ name ] ) {
540
+ nextTick ( fn ) ;
541
+ } else {
542
+ this . once ( name + '-ready' , fn ) ;
543
+ }
544
+ }
545
+ return this ;
546
+ } ;
547
+
499
548
/**
500
549
* Register a `fn` to be fired when all the analytics services are ready.
501
550
*
502
551
* @param {Function } fn
503
552
* @return {Analytics }
504
553
*/
505
554
506
- Analytics . prototype . ready = function ( fn ) {
555
+ Analytics . prototype . _ready = function ( fn ) {
507
556
if ( is . fn ( fn ) ) {
508
557
if ( this . _readied ) {
509
558
nextTick ( fn ) ;
0 commit comments