Google recommends to put the analytics code just before the <body>
tag. I'm trying to integrate ecommerce in my site and it'd be easier to call pageTracker._addTrans
from other places than the footer.
Will it be ok if I change
...
<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-xxxxxx-x");
pageTracker._trackPageview();
} catch(err) {}</script>
</body>
To something more like
<body>
<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-xxxxxx-x");
} catch(err) {}</script>
...
<p>Thanks for your purchase!</p>
<script type="text/javascript">
try{
pageTracker._addTrans(...);
pageTracker._trackTrans();
} catch(err) {}</script>
...
<script type="text/javascript">
try{
pageTracker._trackPageview();
} catch(err) {}</script>
</body>
It can certainly go before the rest of the site's code, but javascript will block the loading of the rest of the page. Which is why they often recommend if you have to load javascript files and it's not important to load them ahead of everything else (or in the <head>
), to put the script tags at the bottom of the page.
I have included Google Analytics code inside the ready event when using jQuery and it works fine too.
$(document).ready(function () {
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"));
try{
var pageTracker = _gat._getTracker("UA-xxxxxx-x");
} catch(err) {};
try{
pageTracker._addTrans(...);
pageTracker._trackTrans();
} catch(err) {};
try{
pageTracker._trackPageview();
} catch(err) {};
});
It is only a recomendation to place the tracker code before the closing body tag. You can also place it in the head or somewhere else.
Google recomends this because in the footer the chance it makes problems by other scripts is more less. But if you put try {} catch (e) {} arround it will be save every where. Just check with firebug if the track Ajax request will be fired.
It's a good practice to place the code before the end of the body only for a matter of performance loading of the web page!
This code can be placed anywhere JavaScript code is acceptable. here is a link to their help documentation on where this should go, and where it can go:
http://www.google.com/support/analytics/bin/answer.py?hl=en_US&answer=55488&utm_id=ad
Hope this helps,
Thanks!