Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 762
Dorad Avatar asked Jun 15 '18 11:06

Dorad


People also ask

What is Google Analytics snippet?

The Analytics tag is a snippet of JavaScript that collects and sends data to Analytics from a website. You can add the Analytics tag directly to the HTML of each page on your site, or indirectly using a tag management system such as Google Tag Manager.

What do you do with the tracking code snippet?

Once you've identified your tracking ID, you'll need to get your tracking code snippet, which can be found on this page as the Global Site Tag ( gtag. js ). The gtag. js is the tracking code for this specific property and you'll need to copy and paste this code to every webpage you want to track on your website.

What can Google Analytics tracking code track?

What Is the Google Analytics Tracking Code? Google Analytics' tracking code (or ID) is a unique identifier that allows Google Analytics to collect data when inserted into a website. This data includes the time users spend on a webpage, search terms used, and how they came to the site.


2 Answers

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

like image 80
Liam Avatar answered Oct 18 '22 23:10

Liam


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.

like image 29
Patrick Hund Avatar answered Oct 19 '22 00:10

Patrick Hund