ankush981
ankush981

Reputation: 5407

ClientId not getting captured

We have three custom dimensions defined in Google Analytics:

And these are being fed from an on-page script:

$(document).ready(function() {
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
        (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
        m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

    function getClientId() {
        try {
            var trackers = ga.getAll(); 
            var i, len;
            for (i= 0, len = trackers.length; i < len;  i += 1) {   
                if (trackers[i].get('trackingId') === 'UA-XXXXXXXX-1')  {
                    return trackers[i].get('clientId');
                }
            }
        }
        catch(e){
            //do nothing
        }       
        return  'false';
    }

    function getSessionId() {
        return new  Date().getTime() + '.' + Math.random().toString(36).substring(5);
    }

    function getTimeStamp() {
        return new Date().getTime();
    }

    ga('create', 'UA-XXXXXXXX-1', 'auto');
    ga('require', 'displayfeatures');
    ga('require', 'linkid', 'linkid.js');

    var clientId = getClientId();
    var sessionId = getSessionId();
    var timeStamp = getTimeStamp();

    ga('send', 'pageview', {
        'dimension1' : clientId,
        'dimension2' : sessionId,
        'dimension3' : timeStamp
    });        
});
</script>

Now, the marketing team tells us that ClientId is not getting captured. They shared data where we had some 24,000 rows, out of which only two had valid client ids. By contrast, Session ID and Hit Timestamp are being captured perfectly.

When I do a quick check on the website (by assigning the code for getClientId() to another temporary function and calling it), I get the ClientId.

I'm really not sure what's causing this to be missed on the live website. Can someone point out something that might be awry?

Upvotes: 0

Views: 1560

Answers (1)

nyuen
nyuen

Reputation: 8907

You should consider loading the GA library as recommended in the <head> section of your site rather than on $(document).ready. This is so that the analytics tracking has the soonest possibility to start tracking user engagements. In addition, if you load the analytics after DOM is ready or after the page has completely loaded, then there is the chance you miss some metrics if, for example, a user lands on your page, and then navigates away before the analytics library has a chance to capture their data.

Upvotes: 1

Related Questions