Kurt
Kurt

Reputation: 1897

Google Analytics - event tracking code in separate <script> than the page tracking code

On a site I'm working on, the main section of the tracking code is located at the bottom of the pages (not my choice of placement, but that's where it is). That code is the main:

var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-XXXXXXXX-X']);
  _gaq.push(['_trackPageview']);
 (function() {
   var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
  ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
 var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

On one specific page, I want to track an event that gets auto launched on page load. What I have for code at the top of the page (and therefore in a separate tag than the above code) is:

function getFile()
{
  if("<%= getFileURL()%>".length>0){
    window.location.href = "<%=getFileURL() %>";
    var _gaq = _gaq || [];
    _gaq.push(['_trackEvent', 'Downloads', '<%= getFileURL()%>']);
  }
}

It doesn't seem to be tracking the event though. I'm sure I'm doing something wrong here and I can take some guesses, but it's not clear enough for me to know exactly what I need to change.

Upvotes: 0

Views: 120

Answers (2)

EkoostikMartin
EkoostikMartin

Reputation: 6911

You need to delay the redirect. Something like this below has worked for me in the past:

function getFile() {
  var href = "<%=getFileURL() %>";

  if(href){    
    _gaq.push(['_trackEvent', 'Downloads', href]);
     setTimeout("gotoUrl('" + href + "')", 100);
  }
};

function gotoUrl(href) {
    window.location.href = href;
};

Upvotes: 1

mike
mike

Reputation: 7177

Two problems with your code:

  1. You're redirecting before tracking the event. For best results (like @EkoostikMartin mentioned), you'll want a slight delay between the event tracking and redirect.
  2. You've got a local _gaq defined inside getFile(), so you're not talking to the actual Google analytics code.

Try:

function getFile() {
  var href  = "<%=getFileURL() %>";
  if (href.length > 0) {
    _gaq.push(['_trackEvent', 'Downloads', href]);
    setTimeout(function(){window.location.href = href}, 100);
  }
}

Upvotes: 1

Related Questions