I made a helper for my javascript in order to track some ajax events, here’s a short version of what it’s set up to be
analytics:{
active: false,
gaq: null,
init: function(gaq){
this.active = true;
this.gaq = gaq;
$('a[href^=\"http://\"]').live('click', function() {
helper.analytics.trackPageview('/outgoing/' + $(this).attr('href'));
return true;
});
},
trackPageview: function(page){
if(this.active === false){
return;
}
this.gaq.push(['_trackPageview',page]);
}
},
And I have the common google analytics setup
<script type="text/javascript">
var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-xxxxxxxx-1']);
_gaq.push(['_setDomainName', '.example.com']);
_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);
})();
$(document).ready( function() {
helper.analytics.init(_gaq);
});
</script>
However in the console logging _gaq results in an object. logging helper.analytics.gaq results in an array, whith new pageviews appended, but the pageview is not being tracked in google analytics.
Why isn’t _gaq being passed to the helper by reference?
When creating the script tag, the ga snippet sets the
asyncattribute to true. Therefore, it’ll load independently from the body. You’ll need to bind an event handler to the ga script tag’s onload event. Something like so:I’ve not tested this, but I think it might work.