diff --git a/angular-segmentio.js b/angular-segmentio.js index 5b3b34d..1373e88 100644 --- a/angular-segmentio.js +++ b/angular-segmentio.js @@ -3,7 +3,23 @@ angular.module('segmentio', ['ng']) function($rootScope, $window, $location, $log) { var service = {}; - $window.analytics = $window.analytics || []; + // Create a temp queue for events fired before analytics loaded + // but do not attempt to create 'analytics' object. + var tempQueue = []; + + + function flushTempQueue () { + if (tempQueue.length) { + // Send the queue of pending events + $window.analytics.push.apply($window.analytics, tempQueue) + tempQueue.length = 0 + } + } + + // Analytics script is loaded callback. + var analyticsLoaded = function() { + flushTempQueue() + } // Define a factory that generates wrapper methods to push arrays of // arguments onto our `analytics` queue, where the first element of the arrays @@ -12,12 +28,15 @@ angular.module('segmentio', ['ng']) return function() { var args = Array.prototype.slice.call(arguments, 0); $log.debug('Call segmentio API with', type, args); - if ($window.analytics.initialized) { + + //Because we didn't overwrite the analytics object we can use + //its presence as a flag that segment.io has loaded. + if ($window.analytics) { $log.debug('Segmentio API initialized, calling API'); $window.analytics[type].apply($window.analytics, args); } else { $log.debug('Segmentio API not yet initialized, queueing call'); - $window.analytics.push([type].concat(args)); + tempQueue.push([type].concat(args)); } }; }; @@ -50,6 +69,7 @@ angular.module('segmentio', ['ng']) script.async = true; script.src = ('https:' === document.location.protocol ? 'https://' : 'http://') + 'd2dq2ahtl5zl1z.cloudfront.net/analytics.js/v1/' + apiKey + '/analytics.js'; + script.onload = analyticsLoaded // Find the first script element on the page and insert our script next to it. var firstScript = document.getElementsByTagName('script')[0];