Skip to content

Commit

Permalink
Merge pull request #404 from alphagov/set-client-id-asynchronously
Browse files Browse the repository at this point in the history
Only make GOV.UK analytics call when GA is ready
  • Loading branch information
boffbowsh authored May 3, 2017
2 parents 733da14 + 8bd1360 commit 0a797cf
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 6 deletions.
14 changes: 8 additions & 6 deletions javascripts/govuk/analytics/govuk-tracker.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,6 @@
var GOVUKTracker = function (gifUrl) {
this.gifUrl = gifUrl
this.dimensions = []
if (global.ga) {
global.ga(function (tracker) {
this.gaClientId = tracker.get('clientId')
}.bind(this))
}
}

GOVUKTracker.load = function () {}
Expand Down Expand Up @@ -118,7 +113,14 @@

GOVUKTracker.prototype.sendToTracker = function (type, payload) {
$(global.document).ready(function () {
this.sendData(this.payloadParams(type, payload))
if (global.ga) {
global.ga(function (tracker) {
this.gaClientId = tracker.get('clientId')
this.sendData(this.payloadParams(type, payload))
}.bind(this))
} else {
this.sendData(this.payloadParams(type, payload))
}
}.bind(this))
}

Expand Down
19 changes: 19 additions & 0 deletions spec/unit/analytics/govuk-tracker.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,14 @@ describe('GOVUK.GOVUKTracker', function () {

var tracker

function setupFakeGa (clientId) {
window.ga = function (cb) {
cb({
get: function () { return clientId }
})
}
}

beforeEach(function () {
tracker = new GOVUK.GOVUKTracker('http://www.example.com/a.gif')
})
Expand Down Expand Up @@ -74,11 +82,22 @@ describe('GOVUK.GOVUKTracker', function () {

describe('sendToTracker', function () {
it('sends when the DOM is complete', function () {
setupFakeGa('123456.789012')

spyOn(tracker, 'sendData')
tracker.sendToTracker('foo')

expect(tracker.sendData).toHaveBeenCalledWith(jasmine.any(Object))
})

it('sets the ga Client ID', function () {
setupFakeGa('123456.789012')

spyOn(tracker, 'sendData')
tracker.sendToTracker('foo')

expect(tracker.gaClientId).toEqual('123456.789012')
})
})

describe('tracking', function () {
Expand Down

0 comments on commit 0a797cf

Please sign in to comment.