Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load Google Analytics from jQuery document ready?

The problem is that GA sometimes takes a little while to load, and my jQuery ready() functions don't run until it's done. I'd like to move the GA code itself to the end of the ready() function. I'm not looking for extra click tracking integration - I just want my ready() scripts to run first.

My questions are: 1) Will moving the GA code break their stat tracking in any way? And, 2) Do I need to emulate their use of two script tags (one that generates the external script tag, and one that calls the function)? If so, why, and what's the best way to do that in a jQuery function?

To explain #2, here's the GA code that currently goes just before the closing body tag:

<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-8704511-1");
pageTracker._trackPageview();
} catch(err) {}</script>
like image 666
Jerph Avatar asked May 12 '09 13:05

Jerph


3 Answers

A similar question here:

  • How to dynamically load Google Analytics (JavaScript)?

And the accepted answer here:

  • Better Google Analytics JavaScript that doesn’t block page downloading
like image 158
viam0Zah Avatar answered Oct 24 '22 01:10

viam0Zah


It looks like Google has tackled this issue as well - see this more recent Stack Overflow question

like image 31
Jeremy Carlson Avatar answered Oct 24 '22 01:10

Jeremy Carlson


The reason there are two script blocks is because the script in the first block inserts a reference to the Google Analytics javascript file between the two blocks. If it would all to be in the same block, the tracker would try to be initialized before it had been loaded. So #2 is definately true, you would need to have or emulate two script tags.

like image 36
janzi Avatar answered Oct 24 '22 03:10

janzi