Right now there's no good solution to this problem. The best you can do is to add a timeout to delay the redirection. Currently there's no callback to the _trackPageview. When it returns it means that it started the tracking, but it's not garanted that it have successfully registered the pageview until the __utm.gif request is complete.
1 sec timeout may be too much. I usually keep the timeout around 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 2 years since I originally initially posted this answer and since then Google Analytics has come a long way.
Now there's a proper 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 have migrated to Universal Analytics using analytics.js the equivalent would be:
ga('create', 'UA-XXXXXXX-X')
ga('send', 'pageview', {
'hitCallback': function() {
window.location.href = newUrl;
}
});
EDIT 2
Here's the more proper way to do this to make sure your code executes even if Google Analytics code is blocked or tampered by an 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
});