Last Updated: February 25, 2016
·
539
· jbasko

Wrap 3rd party tracking code

Startups appear and then they die. Or become unfashionable. Especially the ones providing tools for other startups. One day you want to use intercom.io, the other you want to use mixpanel.com. Do not add calls to their API directly in your code. Have your own tracker and then just update it whenever you change your mind.

My.Tracker = function () {

    this.push = function (command) {
        try {
            this[command[0]].apply(this, command.slice(1));
        } catch (e) {
            // ...
        }
    };

    this.track = function () {
        try {
            var mixpanel = window.mixpanel;
            mixpanel.track.apply(mixpanel, arguments);
        } catch (e) {
            // ...
        }
    };

    this.identify = function (userDetails) {
        try {
            var mixpanel = window.mixpanel;
            mixpanel.identify(userDetails['id']);
            mixpanel.name_tag(userDetails['email']);
            mixpanel.people.set(userDetails);
        } catch (e) {
            // ...
        }
    };

    if (typeof window._my_tracker !== 'undefined') {
        for (command in window._my_tracker) {
            this.push(command[0], command[1]);
        }
    }
};

_my_tracker = new My.Tracker();

Now you can use this tracker in your code:

_my_tracker.push(['identify', {id: 123, email: 'example@example.com'}]);

You can use your tracker before it's even loaded just like the Google Analytics one:

_my_tracker = _my_tracker || [];
_my_tracker.push(['track', 'hello']);

When you decide to change your provider (mixpanel in this example) you just have to update this.track and this.identify or any other public methods you want your tracker will have.