I have a tracking pixel that I need to load in JS, at the click of a button. So the process is as follow :
- The user clicks a link
- I prevent the click (e.preventDefault)
- load the tracking pixel
- Redirect the user
Here is the code :
$('.btn-cta').on('click', function (e) {
e.preventDefault();
$('body').append('<img width="1" height="1" src=".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 wele.
John
I have a tracking pixel that I need to load in JS, at the click of a button. So the process is as follow :
- The user clicks a link
- I prevent the click (e.preventDefault)
- load the tracking pixel
- 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./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 wele.
John
Share Improve this question asked Jul 9, 2015 at 9:43 JohnWolfJohnWolf 1,18714 silver badges29 bronze badges 2-
3
You should redirect in the
onload
event listener on the image. – pawel 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. – somethinghere Commented Jul 9, 2015 at 9:46
1 Answer
Reset to default 4Wait 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 ments)
// otherwise the navigation would be broken.
track.onerror = function(){
window.location.replace( url );
};
track.src = 'http://main.exoclick./tag.php?goal=xyz';
});