Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery pjax and google analytics

I am using PJAX https://github.com/defunkt/jquery-pjax and I was wondering since the whole page does not change what would be the best way to track analytics with google analytics?

like image 468
chopi321 Avatar asked Mar 02 '12 04:03

chopi321


1 Answers

The accepted answer is no longer valid because as Ruy Diaz commented, this was removed from PJAX in this commit.

Here is my solution. On the pjax:end event, set the GA location, and send a pageview.

The pjax:end event is used because it is triggered both "upon following a pjaxed link" (loading from server) and "on back/forward navigation" (loading from cache). See pjax events documentation

$(document).on('pjax:end', function() {
    ga('set', 'location', window.location.href);
    ga('send', 'pageview');
});

Or using the old version of GA

$(document).on('pjax:end', function() {
    if( window._gaq ) {
        _gaq.push(['_trackPageview', window.location.href]);
    }
});

I had to manually set the location variable because it wasn't picking up that it changed.

like image 168
andrewtweber Avatar answered Oct 05 '22 03:10

andrewtweber