I want to track users clicking links to external sites. I'm happy to use the asynchronous version of GA as this allows (in most browsers) the page to continue loading instead of halting at the script tag and waiting for google-analytics.com/ga.js to download and execute.
Google recommends this function:
<script type="text/javascript">
function recordOutboundLink(link, category, action) {
try {
var myTracker=_gat._getTrackerByName();
_gaq.push(['myTracker._trackEvent', ' + category + ', ' + action + ']);
setTimeout('document.location = "' + link.href + '"', 100)
}catch(err){}
}
</script>
<a href="http://www.example.com" onClick="recordOutboundLink(this, 'Outbound Links', 'example.com');return false;">
The problems with this solution:
- It could take 10ms, it could take 300ms for the event to be tracked, but it'll change the page after 100ms no matter what happens. And if the tracking is too slow the page will change before it's been tracked.
document.location =
means the original link is ignored and therefore target=_blank does not open new tabs/windows.