Add a delay for click links for Google Analytics

I was looking for various Javascript snippets to track Google Analytics events. I am using Google Tag Manager. This question is also similar to some questions I posted recently, so I apologize for the smaller pool of users who follow the google analytics tag and see the same thing.

I am currently working with this snippet:

<script type="text/javascript"> $(document).ready(function(){ $('.app-cta a').onClick=_gaq.push(['_trackEvent', 'App', 'Click', 'iOS']); }); </script> 

Inside httpfox, all event parameters (App, Click, iOS) are displayed. But not in Google Analytics.

I am told that a fairly common practice is to add a delay to the link, somewhere between 5 and 500 milliseconds. This is because, as I was told, sometimes the browser gets to a new site before it can transfer analytics parameters.

There may be alternative ways to fix this, but for my own curiosity, find out how to use Javascript for analytics, how do I integrate setTimeout into the above code?

I tried this:

 <script type="text/javascript"> $(document).ready(function(){ setTimeout(function(){ $('.app-cta a').onClick=_gaq.push(['_trackEvent', 'App', 'Click', 'iOS']); }); },500); </script> 

But does this delay the Google Analytics tag from transmitting data, and not delay the click? I checked and this did not solve my problem.

+4
source share
3 answers

Use Google Analytics hitCallback

You can set up a custom callback on the tracker using the code registered here.

You might end up with something like:

 $( ".app-cta a" ).click(function(e) { var location = $(this).attr('href'); //get the link location e.preventDefault(); //disable the link action _gaq.push(['_set','hitCallback',function() { window.location = location; //action link after callback }]); _gaq.push(['_trackEvent', 'App', 'Click', 'iOS'); //trigger Track Event return !window._gat; //fallback in case Google Analytics hasn't loaded. }); 
+3
source
 Something like that should work $(function () { $('.app-cta a').click(function (e) { e.preventDefault(); var $this = $(this), timer = 500, target = $this.attr('target'), href = $this.attr('href'); _gaq.push(['_trackEvent', 'App', 'Click', 'iOS']); setTimeout(function () { if (target) { window.open(href, target); } else { window.location = href; } }, timer); }); }); 
+2
source

I am not very good at Google Analytics, but the code below will execute your _gaq.push() method and then redirect the page 500 ms later.

 $(document).ready(function() { $('.app-cta a').on('click', function (e) { var location = $(this).attr('href'); e.preventDefault(); _gaq.push(['_trackEvent', 'App', 'Click', 'iOS']); setTimeout(function () { window.location = location; }, 500); }); }); 
+2
source

Source: https://habr.com/ru/post/1496616/


All Articles