In the old version of Google Analytics you could just add var _gaq = _gaq || [];
on the top of your javascript files, which would let you push events and transactions before GA had fully loaded.
With Universal Analytics you no longer use .push()
, so what is the proper way to create the ga
object in external files where Google Analytics might not have loaded yet but you need to push events and transactions?
But importantly for Google Analytics, JavaScript allows your computer to send and receive messages to other computers connected to the internet. When you visit a site that has implemented Google Analytics, the site will ask your computer to temporarily download some JavaScript instructions from Google Analytics.
You can put it anywhere you want on page, and ll run anywhere on the page whether it's in the head or the body. But according to Google support (Add the tracking code directly to your site) it is recommended to it in the head tag, paste it immediately before the closing </head> tag.
Google Analytics relies on two pieces of browser technology to track website users: cookies, and JavaScript.
The Immediately-Invoked Function Expression in the Google Analytics snippet handles the creation of that object. In the snippet you see the following:
i[r] = i[r] || function() {
(i[r].q = i[r].q || []).push(arguments)
}
We know from the parameters passed to the IIFE that i = window and r = "ga":
(function(i, s, o, g, r, a, m) {
//...
})(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
In un-uglyfied JavaScript, the snippet reads as such:
window['ga'] = window['ga'] || function() {
( window['ga'].q = window['ga'].q || []).push(arguments)
}
So by calling the global function ga
, you are essentially creating an array that serves as the queue (if it doesn't already exist) and pushing values to the queue.
In Universal Analytics, calling this function:
ga('create', 'UA-XXXX-Y', 'auto');
Is the same as this in the previous version of GA:
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXX-Y']);
More info can be found in the Google dev docs.
You don't need to redefine the ga
function since it already is defined in the tracking snippet. All you have to do is use the ga
object in your external file and you are good to go. ga
already is a global object, so no need to scope it.
You also don't want to be pushing anything into ga
object before you at least run the line that creates the tracker:
ga('create', 'UA-XXXX-Y', 'auto');
If you d chances are the hit won't get through and won't reach your account.
Make sure that whatever external file you use you include it after the tracking snippet in your site, or maybe include the tracking snippet in the external file at the top.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With