From 8bd1360d9f2e6a8966824dd67f4935598c0d4e02 Mon Sep 17 00:00:00 2001 From: Paul Bowsher Date: Tue, 2 May 2017 13:57:54 +0100 Subject: [PATCH] Only make GOV.UK analytics call when GA is ready MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit We want to send the `gaClientId` with our GOV.UK analytics payload, but due to asynchronous loading we may not have actually fetched it from the GA library by the time `sendToTracker` is called. If GA is enabled on this page, we now wrap the call to `sendData` in the “ga ready” callback function and make sure we set the clientId first. --- javascripts/govuk/analytics/govuk-tracker.js | 14 ++++++++------ spec/unit/analytics/govuk-tracker.spec.js | 19 +++++++++++++++++++ 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/javascripts/govuk/analytics/govuk-tracker.js b/javascripts/govuk/analytics/govuk-tracker.js index b3408528..ef73fc8d 100644 --- a/javascripts/govuk/analytics/govuk-tracker.js +++ b/javascripts/govuk/analytics/govuk-tracker.js @@ -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 () {} @@ -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)) } diff --git a/spec/unit/analytics/govuk-tracker.spec.js b/spec/unit/analytics/govuk-tracker.spec.js index ca1d0f6a..dd0621ee 100644 --- a/spec/unit/analytics/govuk-tracker.spec.js +++ b/spec/unit/analytics/govuk-tracker.spec.js @@ -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') }) @@ -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 () {