This time we’ll take a look at two different, JavaScript-y features of Google Analytics and Google Tag Manager. Callback as a concept should be familiar to anyone who’s ever used a programming language. It’s basically a piece of code that is passed as an argument to some function, so that when this second function has completed, the callback is executed.

For web analytics, callbacks are hugely important, since they allow you to impose a firing order for your asynchronous tags. Asynchronous tags, as you might know, abhor order and precision, so sometimes it’s necessary to use a callback to have at least an inkling of predictability in your tag jungle.

Tip 6: hitCallback and eventCallback

Here’s the difference:

hitCallback - hitCallback is a feature of the analytics.js collection library. It lets you provide a callback function for each tag separately. If you want to, for example, fire some tag directly after your pageview has fired, you might want to use hitCallback to push an event into dataLayer, and then use that event to fire your second tag. Or you might do something really wacky, such as use hitCallback to fire a single tag multiple times.

The key thing here is to make sure that the Custom JavaScript Macro which holds the callback function returns a function which does all the work. This is important, since otherwise the function expression in your callback macro would fire TWICE: first when the tag is written and executed, and again when the callback is fired.

eventCallback - eventCallback is pure GTM. If you push a dataLayer event into the message queue, you can also push the eventCallback key as well. The value of the key would be the callback function. As soon as all tags which fire on the event that you pushed have executed, your callback function will fire.

dataLayer.push({
    'key1' : 'value1',
    'key2' : 'value2',
    'event' : 'fireTags',
    'eventCallback' : function() {
        alert('ALL tags which fire on {{event}} equals fireTags have now fired');
    }
});

So in the code example above, as soon as all tags that have the firing rule {{event}} equals fireTags have executed, the function in the callback will fire.