Reputation: 2052
I want to track clicks that users on my page. But I'm a little confused. Looking at this code:
<a href="http://example.com" onClick=”_gaq.push(['_trackEvent', 'External Link', 'Twitter Link', 'Follow Us - Words']);”>Follow Us</a>
^ What if user get's redirected to http://example.com
before google analitics tracks - then what? Am I right that that example has a race condition?
Upvotes: 2
Views: 598
Reputation: 91497
There is no race condition. The click handler is called and executes completely before page navigation starts. That click handler creates an ajax request whose response is inconsequential. The ajax request is started before page navigation is started.
Don't be fooled by the method name. According to google:
This function is named push so that an array can be used in the place of _gaq before Analytics has completely loaded. While Analytics is loading, commands will be pushed/queued onto the array. When Analytics finishes loading, it replaces the array with the _gaq object and executes all the queued commands. Subsequent calls to _gaq.push resolve to this function, which executes commands as they are pushed.
While initially, .push()
merely pushes commands into an array, once Analytics has loaded, those commands are executed immediately.
Upvotes: 3
Reputation: 292
You can do this:
With jQuery:
$('a').on('click', function(e){
e.preventDefault();
var $el = $(this);
_gaq.push(['_trackEvent', 'External Link', 'Twitter Link', 'Follow Us - Words']);
setTimeout(function(){
window.location.href = $el.attr('href');
}, 100);
});
Without jQuery:
document.getElementById('someIdOfLink').addEventListener('click', function(){
return false;
var $el = this;
_gaq.push(['_trackEvent', 'External Link', 'Twitter Link', 'Follow Us - Words']);
setTimeout(function(){
window.location.href = $el.getAttribute('href');
}, 100);
});
hope help you!
Upvotes: 0