04
Jun '15

This all related to a bit of a quirk of the way javascript operates on click events. You would think that in order to triggering analytics on a download link you could just add a click handler to the link and it would be all good. Unfortunately this is not the case. As analytics triggers are pretty much universally ajax calls the script will continue before it gets a response, and if that continuation leads to a download (or indeed simply to navigation away from the current page) then the analytics trigger will fail. My solution involves forcing the browser to give analytics a couple of seconds to return before completing:

$(document).on('click', 'a.download-file', function() {
    var element = $(this);

    ga('send', 'event', 'File', 'Download', 'File Download');

    setTimeout(function() {
        window.location.href = element.attr('href');
    }, 2000);

    return false;
});

Of course it’s not bullet-proof but it’s my go-to solution for these situations.