How can I make sure _gaq.push() works good? - javascript

Our client asked us to implement the following Google Analytic code:
_gaq.push(['SX0._setCustomVar', 4, 'xxxx', "yyyy", 2]);
So I've made this, and now I'm looking for a way - how can I check that everything is correct (without actually building GA report)? I haven't did this before - so please sorry if the answer is obvious.
Thanks.

You'll need to define the _gaq variable and load in the analytics script from googles server. After that, you should be able to call the 'push' method.
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXXX-X']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
// tracks hit for /some/page/
_gaq.push(['_trackPageview', '/some/page']);
After that's done, load up the page in your browser, open up the console, and look in the network tab. Try loading a few pages, and verify that it's asynchronously pushing data to googles servers.
Google uses a .gif image for tracking, so you might try filtering by image and to find request for a file called __utm.gif
If you're still having trouble finding it, you might try the tag debugger plugin by ObservePoint for Chrome or the Official Tag assistant plugin by Google

Use the Analytics debugger extension for Chrome. Another useful extension (although it will not help you with custom vars) is the Google Tag Assistant (which will also check other Google tags such as adwords conversion tags and the like).

Related

Tracking Multiple Domain Names Under One Google Analytics Account

I've read the docs here about 100 times and I can't figure this out.
I have a platform that basically creates spoofed domain names on top of one backend:
mysite.com
yourface.com
example.com
Since all domains point to the same root index file, I would like to have one Google Analytics tracking code that I can put in the footer that will track activity on all these domains.
Right now, I am using the following, and it only tracks activity on mysite.com (not the other ones):
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXXXX-1']);
_gaq.push(['_setDomainName', 'mysite.com']);
_gaq.push(['_setAllowLinker', true]);
_gaq.push(['_getLinkerURL','mysite']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
I know I can set up separate profiles but that defeats the point of needing aggregate data.
Any ideas?
The culprit is probably this
_gaq.push(['_setDomainName', 'mysite.com']);
because that limits the GA cookie to the mysite.com domain. If you drop the setDomainName call alltogether it should track all domains where the code is deployed (and you'll need to filter by hostname if you want to see data for one particular domain).
That is, if I understood you correctly and your domains use the same backend but are independent on the frontend; if there is traffic between the domains you'll need to set up cross domain tracking to track correctly (else user sessions will end when a user visits another domain).
From the Google Analytics dashboard, click on Admin at the right to get to the Account Administration page. Then click on the name of your account, and you'll be taken to a list of things you're using Analytics to track. Then click on the New Property button to add the next website to your account. Each website gets its own javascript code that must be generated by Google Analytics before you install it in your website, so you have to go through this process for each website you want to track.

If Google Analytics goes down, how do I keep my site working?

Ok it's 19 Jan 2013 22:30 NZST and most of the internet seems to have come to a crawl as Google Analytics seems to be running really slow. Stackoverflow, Firefox.com, reddit and google searches are slow. Most importantly for me, my production business website is running slow or not loading at all. No it's not just my connection I tested it on my phone with 3G as well. Sites without Google Analytics seemed to be running fine.
Here's a few screenshots of what happens
This is in the bottom left corner of the Firefox window. It will sit there for 20+ seconds like that. I'd like it to go away after 3 seconds if it can't connect.
This spinning green image is in the Firefox tab and just sits there making it look like the page is still loading for 20+ seconds. I'd like it to go away after 3 seconds if it can't connect.
Now it may not be Google Analytics, my country' international gateway may be running slow or something. But evidence strongly suggests it might be Google Analytics. Now even if it isn't Google Analytics then I'd still be interested in some methods to counter it if the service is completely down. So hypothetically lets assume there's a massive fire at the datacenter of Google Analytics and the fire suppression systems failed. Now Google Analytics goes completely offline for several days. No backup servers. No standby datacenters. Hypothetical scenario ok. Now my site still needs to run as I can't afford to have my site reliant on Google Analytics service being up. But the analytics functionality would be good to have as an added bonus if the service is actually running in a timely manner.
Ok so I'm throwing out some ideas here:
Is there's a timeout I can add to my script that will cancel the connection to Google Analytics and halt the request/download if it's taking too long? Then it would continue loading my site after 2 seconds.
Or better yet, perhaps it can just load my site completely, then send a request off to Google Analytics using Ajax after my site is completely finished loading? Why doesn't it do this by default?
Here's the code we have to work with which is currently inserted just before the closing </body> tag.
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-123456789-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
Now, what are some methods I could employ that would fix this hypothetical disaster scenario and give my website continuity while Google Analytics is down? I'm interested in either potential software or hardware solutions. Assume I have full access to a Linux VPS which my PHP/MySQL/HTML5 website is running on.
Also, what's the authoritative answer on this: some people say place the code before the closing </head> tag. Others say place it before the closing </body> tag. Which is the best way?
Many thanks
Solution Update
Ok I've found out what works with help from Jaspal. The solution is below.
<script type="text/javascript">
// Load Google Analytics after my site has completely loaded
// Then when Google Analytics request is made it won't show any visuals in the browser
setTimeout(loadGoogleAnalytics, 5000);
// Setup _gaq array as global so that the code in the ga.js file can access it
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-123456789-1']);
_gaq.push(['_trackPageview']);
/**
* Loads Google Analytics
*/
function loadGoogleAnalytics()
{
var srcUrl = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
$.ajax(
{
url: srcUrl,
cache: true,
dataType: "script",
success: function(data)
{
console.log('got the script');
},
error: function()
{
console.log('failed to get the script');
},
timeout: 5000
});
};
</script>
Basically why it works is because there is a setTimeout for 5 seconds. This gives my page enough time to load all the content, JS, CSS, images etc. Then after that it kicks off the $.ajax request and downloads ga.js and __utm.gif which is actually sending the data to Google Analytics. After that initial 5 seconds, basically all the browser visuals I mentioned earlier disappear and the Google Analytics request happens silently in the background with no loading visuals for the browser user. Then I tried blocking Google Analytics with the host file and I still don't get any browser visuals - perfect.
It should be noted that the timeout: 5000 property in the $.ajax request doesn't appear to do anything. Originally I was hoping it would abort the request if it couldn't get data for 5 seconds but there's a note in the API docs saying
In Firefox 3.0+ only, script and JSONP requests cannot be cancelled
by a timeout; the script will run even if it arrives after the timeout
period.
I'll leave it in there anyway just in case. From my testing if Google Analytics can't be reached (from observing the Net/Network panel in Firebug/Chrome) then it will abort the request after 21-23 seconds in Firefox and 16 seconds in Chrome. This may be some TCP timeout. I'm not worried about that anyway as it's timing out silently and the user will not notice as there's no loading visuals in the browser.
I have accepted Jaspal's answer below and awarded him the bounty as his solution was critical to solving this. However his solution still has loading visuals appearing in the browser. So I believe the solution posted here using the setTimeout (a slight modification on his original one) is the way to go and is tested to be working 100% for me.
Given where it's loaded, the rest of your site would load before the request to Google Analytics. Plus GA is loaded asynchronously, not halting the execution of any of your code, so I really don't see there being an issue.
Latest Approach :
We allow ga to load normally.
We store a reference to ga dom element in a global variable (gaClone).
We set a timeout of 30seconds. We also set another global variable (loadedGoogleAnalytics) and set it to 0 initially. When ga loads, we set this variable to 1. On the timeout expiry, we check whether ga was loaded or not. If not, we delete the dom element ga.
<script type="text/javascript">
var loadedGoogleAnalytics = 0;
var gaClone;
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-123456789-1']);
_gaq.push(['_trackPageview']);
_gaq.push(function() {
loadedGoogleAnalytics = 1;
//console.log('GA Actualy executed!');
});
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
gaClone = ga;
})();
setTimeout(function() {
//console.log('timeout fired');
if (loadedGoogleAnalytics != 1) {
gaClone.parentNode.removeChild(gaClone);
}
}, 30000);
</script>
[I have verified this approach with one of my actual GA accounts and i am able to see all the realtime tracking]
Previous Approach
[Note: Ga does not execute if we try to place it in (document).ready();]
[This solution does not work]
<script type="text/javascript">
$(document).ready(function() {
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-123456789-1']);
_gaq.push(['_trackPageview']);
srcUrl = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
$.ajax({
url: srcUrl,
cache: true,
dataType: "script",
success: function(data) {
//console.log('got the script');
},
error: function() {
//console.log('failed to get the script');
},
timeout: 30000
});
});
</script>
Hope this helps
You could host a copy of www.google-analytics.com/ga.js on your own server and load it from there. If you do go that route, I'd set up a cron job to periodically fetch ga.js to make sure you've got the most recent version.
Regarding tracking code placement: one of the main reasons for placing the tracking code earlier in the page (before </head>) has to do with visitors who leave the page quickly (possibly before the entire page has rendered). In that case, you're more likely to collect some data the sooner your tracking code is executed.
Trying to fix something that isn't broken
If you want to use Google analytics you are going to need to communicate with there server some how, period. There service, as pointed out by many of the other answers, run asynchronously meaning it doesn't prevent your site from running what so ever. The 'loading visuals' are there to show something is loading... there is very little you can do about this.
You have two options; put up with Google analytics or use some server side script to run analytics.
If the website is hanging it is because of something else.
Edit
Also not including GA immediately also reduces the accuracy of the stats; bounce rates in particular will not be correct.

Do i need a running website over internet in order to access Google analytics Data using Google API

I am new to Google analytics API. I want to access my Google Analytics Data using its API.I have a local website which is deployed on IIS over a LAN.Using this setup can i access google analytics data by using its API or i need a website running over the internet.If yes please suggest how can it be done using javascript.
Google Analytics works by sending information to Google servers whenever someone visits your HTML page (doesn't need to be on the web). However you need access to the internet to send data to the Google servers. You can track any "website" if you make an account on Google Analytics and simply add the code below to whichever page you wish to track (before the </head> tag, as Google says):
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'TrackingID']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
The TrackingID must be replaced by the tracking ID for your Google Analytics account.

Can't push javascript variable into array

I want to push a javascript variable into an array. Specifically, I want to push a Google Analytics account ID (UA-XXXXXXXX-X) into the Google Analytics javascript tracking code in the footer of my site.
(function($) {
var jsvars = {"columns":"1","mobilemenu":"1","googleanalytics":"UA-XXXXXXXX-X"};
var googleanalytics = jsvars.googleanalytics;
/* hit run to to confirm the googleanalytics variable is available */
alert (googleanalytics);
var _gaq = _gaq || [];
/* I want to push the googleanalytics variable into the array */
/* When I view source, it does not show as UA-XXXXXXXX-X, it just shows as googleanalytics */
_gaq.push(['_setAccount', googleanalytics]);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
})(jQuery);
http://jsfiddle.net/robflate/2MnM7/
Thanks.
Extending Pointy's comment to an answer, you can't use your browser's "view source" function to see what you're looking for. "View Source" will show the JavaScript as you wrote it. It won't show you what any of the values are at runtime, etc. For this, you'll want a decent JavaScript debugger - now built-in to all major web browsers. (Or use Firebug for Firefox.)
If you set a debugger breakpoint on this line, you'll be able to see that googleanalytics is UA-XXXXXXXX-X. This is similar to what you already demonstrated yourself with your alert line.
This is not really an improvement on the answer, but some tips for debugging Google Analytics. The original poster mentioned that he was using chrome, which is a good thing. In chrome you can first of all pull up the JavaScript debug console using the key combo CTRL-SHIFT-J. For Google Analytics specific information, you can also download the extension for GA debugging built for Chrome. This extension allows you to see pretty much everything you would want to know about your Google interactions in the debug console.
Also, fiddler2 is a great resource for debugging JavaScript. The second link below has a great video tutorial on how to use fiddler to give you a great deal of control over the http interactions, especially when using the autoresponder function to supply local copies of .js files that would normally be loaded from your web server.
A couple of links that helped me:
http://www.webanalyticsworld.net/2012/01/basics-of-debugging-google-analytics-code-ga-chrome-debugger-and-other-tools.html
http://www.webanalyticsworld.net/2012/02/debugging-google-analytics-code-ii-a-tutorial-video-on-fiddler%E2%80%99s-inspector-and-autoresponder-functions.html

ga.js on server where my site is hosted

I use the next code from Google for Analytics:
<script type='text/javascript'>
var _gaq = _gaq || [];
_gaq.push(['_setAccount', '############']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();
</script>
And I use minify library for merging all JS files into the one. And I want to include ga.js to it. Can I use ga.js from my server and how?
Sure you could use it from your server. Just download it and include it locally instead. It's even already minified. The thing is, you probably don't want to do that. Such a file is usually distributed from a CDN. There are a couple of advantages to this:
If a lot of sites include it from there, chances are that your users will already have it in their cache and will not need to download it
Those CDNs have distributed servers around the world. It will automatically download it from the closest source to your users, which is better than what you can guarantee with your server.
You will also miss out on possible new features being added.
You can read Google's word on that.
In short, juts leave it on GA's servers.

Categories