Now there is no good solution to this problem. The best you can do is add a timeout to delay the redirect. There is currently no callback in _trackPageview. When he returns, it means that he started tracking, but did not guarantee that he successfully registered the pageview until the __utm.gif request was completed.
1 timeout may be too long. I usually save a timeout of about 200-400 ms.
var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-XXXXXXX-X']); _gaq.push(['_trackPageview']); _gaq.push(function () { setTimeout(function(){ window.location.href = newUrl; }, 200); });
EDIT:
It's been two years since I originally posted this answer, and since then Google Analytics has come a long way.
Now there is the right way to do this:
var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-XXXXXXX-X']); _gaq.push(['_set','hitCallback',function(){ window.location.href = newUrl; }]); _gaq.push(['_trackPageview']);
And if you switched to Universal Analytics using analytics.js, the equivalent will look like this:
ga('create', 'UA-XXXXXXX-X') ga('send', 'pageview', { 'hitCallback': function() { window.location.href = newUrl; } });
EDIT 2
Here's a better way to do this, to make sure your code runs even if the Google Analytics code is blocked or modified by the extension or adBlocker.
var t = undefined; var myCode = function(){ window.clearTimeout(t); t = undefined; window.location.href = newUrl; }; t = setTimeout(myCode, 3000); ga('create', 'UA-XXXXXXX-X') ga('send', 'pageview', { 'hitCallback': myCode });