Dorad
Dorad

Reputation: 3713

What is the meaning of Google Anlaytics async tracking snippet?

Google provides the following code snippet in the "Adding analytics.js to Your Site" guide:

window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;

Is this piece of code initializes Google Analytics? How?

Upvotes: 5

Views: 107

Answers (2)

Liam
Liam

Reputation: 29634

Lets break it down

window.ga=

is assigning a variable to ga on the windows object

window.ga||function(){...}

Because of shorting this will either assign the existing window.ga or invoke the function. This could be thought of as:

if(!window.ga){
    window.ga = function(){...}
}

This

(ga.q=ga.q||[])

Is using shorting, like above, to assign an array to ga.q (windows.ga.q) if one doesn't already exist. It then push arguments to this array. So ga ends up being a function that pushes arguments into an array.

It then

ga.l=+new Date;

this assigns (ga.l=) the date as a number (+new Date) using a unary operator.

So this code ultimately creates an object ga with a function that creates an empty array when first invoked (q) and then push arguments to this array. It also creates a date interger (l).

The code has been minified to get it on one line and to reduce it's size. It's also written in such a way that if an object already exists it's not overwritten.

why? Well I think @Patricks answer covers that

Upvotes: 4

Patrick Hund
Patrick Hund

Reputation: 20236

Yes and no – it is part of the initialization of Google Analytics, but not all of it.

What it does is check if the GA library has already been loaded (through an async script tag). If not, it creates an array (ga.q) that caches all tracking events that are created before the library is done loading.

When loading GA is done, the library then processes those queued tracking events.

Upvotes: 3

Related Questions