Search code examples
javascriptgoogle-analyticsanalytics

Google Analytics code: can it go before in the document?


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>

Solution

  • 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.