0

I am using analytics.js. However, I do not load Google Analytics along with the analytics.js script as I am waiting for some data to come in first.

Hence I call ga('create', googleKey, 'auto'); at some point later. This script should always execute, but I want to be 100% sure. Thus, I want to invoke the function in my controller but only in case it has not been called before.

Thus, how can I make sure that it has been called and executed before?

I thought that window.GoogleAnalyticsObject helps me here. But it seems, that this only tells me that ga is in use and not exactly when it is loaded and if it is loaded.

Is there any work around?

Dribel
  • 465
  • 1
  • 10
  • 24

1 Answers1

0

The best solution is to check the pixel request. Create a recursiv function or a interval function. The request is a simple img with this base: https://www.google-analytics.com/collect

e.g

        function checkAnalyticsPixel(){
        var analyticsPixel = false;
        var imgs = document.getElementsByTagName('img');

        for(var i = 0; i < imgs.length; i++){
            var img = imgs[i];

            if(!!img.src.match("google-analytics.com/collect")){
                analyticsPixel = true;      
            }
        }

        if(!analyticsPixel){
            setTimeout(checkAnalyticsPixel, 1000);
        }else{
            return true;    
        }
    }

    checkAnalyticsPixel();

It is also a good idea to add a counter for logging. You can also search other characteristics in the request. A pageview request looks like this:

https://www.google-analytics.com/collect?v=1&_v=j41&a=707797589&t=pageview&_s=1&dl=[URL]&ul=en-us&de=UTF-8&dt=[PAGETITLE]&sd=24-bit&sr=1920x1080&vp=1296x992&je=0&fl=21.0%20r0&_u=QCCAgAAB~&jid=1841853851&cid=253920917.1460537916&tid=UA-39805455-4&gtm=[GTMID]&cg1=beauty&z=1871236975

Edit: Analytics deletes the Pixel. You can override the appendChild. It's not a really nice solution but it could work. The override has to be the first in your script.

var appendChildPrototype = Element.prototype.appendChild;
Element.prototype.appendChild = function(){
    appendChildPrototype.apply(this, arguments); 
    for(var i = 0; i < arguments.length; i++){
        var element = arguments[i];
        if(element.nodeName == "IMG" && element.src.match("google-analytics.com/collect")){
            console.log("ANALYTICS!");
        }
    }
};
Citrullin
  • 2,269
  • 14
  • 29
  • How does the pixel check exactly tell me if analytics is fully loaded. I just integrated your code snippet. it does not seem to tell me what I need to know? – Dribel Apr 22 '16 at 11:34
  • i tested this solution. Doesn't work because google deletes the inserted pixel. That's really bad. – Citrullin Apr 22 '16 at 11:51