Skip to content

Instantly share code, notes, and snippets.

@philsawicki
Last active August 29, 2015 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save philsawicki/140a9a0e36068f30e5f7 to your computer and use it in GitHub Desktop.
Save philsawicki/140a9a0e36068f30e5f7 to your computer and use it in GitHub Desktop.
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