Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
That may sound surprising and even counter-intuitive, but for a some of your users, your Analytics implementation might be breaking your website.

Your Analytics might be Breaking your Website.

<script type="text/javascript">
/**
* Function that tracks a click on an outbound link in Google Analytics.
* This function takes a valid URL string as an argument, and uses that URL string
* as the event label.
*/
var trackOutboundLink = function (url) {
ga('send', 'event', 'outbound', 'click', url, {
'hitCallback': function () {
document.location = url;
}
});
}
</script>
<a href="http://www.example.com" onclick="trackOutboundLink('http://www.example.com'); return false;">
Check out example.com
</a>
/**!
* Function that tracks a click on an outbound link in Google Analytics.
* This function takes a valid URL string as an argument, and uses that URL string as the
* event label.
*
* In the case where the "analytics.js" library is not loaded (either because the event
* was triggered too early in the page lifecycle or because the library was blocked by an
* extension), redirect the user to the intended destination.
*
* @param {String} url The URL to navigate to after recording a Custom Event in Analytics.
* @return {void}
*
* @author Philippe Sawicki (http://philippesawicki.com)
* @copyright Copyright 2015 Philippe Sawicki (http://philippesawicki.com)
*/
var trackOutboundLink = function (url) {
if (ga.q) {
// Analytics has not loaded yet or was blocked:
window.location = url;
} else {
ga('send', 'event', 'outbound', 'click', url, {
'hitCallback': function () {
window.location = url;
}
});
}
}
<script type="text/javascript">
/**!
* Prevents Analytics implementation from breaking site features due to user-installed
* extensions like Ghostery.
*
* @author Philippe Sawicki (http://philippesawicki.com)
* @copyright Copyright 2015 Philippe Sawicki (http://philippesawicki.com)
*/
(function ($) {
if (typeof $ !== 'undefined') {
$('.js-ga-outbound-link').on('click', function (event) {
if (!ga.q) {
event.preventDefault();
var destinationLink = $(this).attr('href');
ga('send', 'event', 'outbound', 'click', destinationLink, {
'hitCallback': function () {
window.location = destinationLink;
}
});
}
}
}
})(jQuery);
</script>
<a href="http://www.example.com" class="js-ga-outbound-link">
Check out example.com
</a>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment