23 August 2013

jQuery Mobile and Google Analytics

Working from the tech.agilitynerd blog I needed to make some changes.

I am following the GA instructions and loading the aynschronous code via a PHP file, but I find that the minified code given by GA directly does not work, so am using the code snippets from the documentation instead.

var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-7920205-5']);
//_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);
})();

Note that I commented out the _trackPageview call, as otherwise I register the first page twice.
Then I have the following 

$(document).on('pageshow', "div:jqmData(role='page')", function (event, ui) {
var url = '';
var hash;
    try {
console.log('ga '+url);
    _gaq.push(['_trackPageview', url]);
} catch(err) {}
});

I use the pageshow event rather than pageinit as the URL is only updated by the latter event.

No comments: