JohnWolf
JohnWolf

Reputation: 1187

Tracking pixel with javascript

I have a tracking pixel that I need to load in JS, at the click of a button. So the process is as follow :

  1. The user clicks a link
  2. I prevent the click (e.preventDefault)
  3. load the tracking pixel
  4. Redirect the user

Here is the code :

$('.btn-cta').on('click', function (e) {
   e.preventDefault();
   $('body').append('<img width="1" height="1" src="http://main.exoclick.com/tag.php?goal=xyz">');
   window.location.replace($(this).attr('href'));
});

My problem is that not 100% of the people who click are tracked, seems like about 40/50% of them are not tracked. I don't see another method to do this, do you have a better idea to track this kind of thing in JS ?

All ideas welcome.

John

Upvotes: 1

Views: 8455

Answers (1)

pawel
pawel

Reputation: 36965

Wait for the image to load, then redirect.

$('.btn-cta').on('click', function (e) {
   e.preventDefault();

    var url = $(this).attr('href');
    var track = new Image();
    track.onload = function(){
        window.location.replace( url );
    };
    // in case the tracking server is down or misconfigured (see comments)
    // otherwise the navigation would be broken.
    track.onerror = function(){
        window.location.replace( url );
    };
    track.src = 'http://main.exoclick.com/tag.php?goal=xyz';
});

Upvotes: 4

Related Questions