1

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

2
  • 3
    You should redirect in the onload event listener on the image. Commented Jul 9, 2015 at 9:44
  • 1
    @Pawei has it right: you are forwarding before the image is likely to be properly requested so the request will be cancelled when you redirect. Commented Jul 9, 2015 at 9:46

1 Answer 1

4

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';
});
Sign up to request clarification or add additional context in comments.

8 Comments

So the image gets loaded fine, but the onload function does NOT get executed. I don't get any error though. Maybe it's because I get this : "Resource interpreted as Image but transferred with MIME type text/html". Any ideas ?
@JohnWolf it seems to be the case. Add an onerror event handler so you'll see it triggered when requesting this image: jsfiddle.net/unj4haqn/1
yea I thought so. These guys are not good enough to give a proper MIME type. I'll look for another solution.
@JohnWolf then add the redirect to the onerror listener as well. While it works and records your hits it's OK, and if the third-party server is down it still won't break your website for the visitors (i.e. you should handle the onerror anyway).
Smart! I will check the data in the next 24 hours to see if it matches better. thanks a lot.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.