Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 23 additions & 3 deletions angular-segmentio.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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));
}
};
};
Expand Down Expand Up @@ -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];
Expand Down