September 2, 2010

Add the Google Analytics Tracking Code

OK, this part is really easy. Once you’ve signed up for your Analytics account, Google will give you a tracking code. It will be a number that looks like “UA-xxxxxx-x”. Copy this tracking code.

Log in to your Magento admin panel. Go to System -> Configuration. In the left hand menu, click on the “Google API” tab under the Sales heading and open the Google Analytics accordion menu. Set Enable to “Yes” and paste the Google tracking code in the Account Number field.

Magento Google Analytics Tracking Code Setup

Click “Save Config” at the top right and you’re done.

Top or Bottom?

If you’ve ever checked you may notice that the Google Analytics tracking code was typically placed at the bottom of the page, just before the </body> tag. If you’re running Magento 1.4.x.x, you may notice that the analytics code is now placed right at the top of the page.

Google’s original code looked like this:

<!-- BEGIN GOOGLE ANALYTICS CODE -->

<script type="text/javascript">
//<![CDATA[
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">
//<![CDATA[
var pageTracker = _gat._getTracker("UA-xxxxxxxx-x");
pageTracker._trackPageview("/");
//]]>
</script>
<!-- END GOOGLE ANALYTICS CODE -->

The old code could slow down the pageload time while Google loaded some fairly hefty javascript libraries to handle the analytics tracking. While the library downloaded, nothing else could happen on the page. Slow page load times make for bad user experience, and with Google’s recent changes in it’s Page Rank algorithms, page load times have an impact on SEO. By placing the code snippet at the bottom of the page, it would ensure that the analytics library was the last thing done on the page.

One concern with this method was that if a user bounced or otherwise left the page before the library downloaded, then any tracking of that event was lost.

Google recently changed the javascript code snipped to utilize ajax to asynchronously handle loading the libraries. This means that the time to load the library is no longer a factor. Google’s new best practices suggest that the code snippet should be added close to the top of the page so that all page events will be captured no matter how fast the user reacts.

Google’s new ajax code snippet looks like:

<!-- BEGIN GOOGLE ANALYTICS CODE -->

<script type="text/javascript">
//<![CDATA[
    (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';
        (document.getElementsByTagName('head')[0] || 
document.getElementsByTagName('body')[0])
.appendChild(ga);
    })();

    var _gaq = _gaq || [];
    _gaq.push(["_setAccount", "UA-xxxxxxxx-x"]);
    _gaq.push(["_trackPageview", "/"]);
//]]>
</script>
<!-- END GOOGLE ANALYTICS CODE -->

Configuring Analytics Code in Magento

If you are inclined to update Magento 1.3.x.x to the new asynchronous code snippet or want to move the code snippet around the site, there are two files you’ll want to concern yourself with.

Change the old ga.js Code to the Asynchronous

The first is the code snippet itself. It is located in ‘/app/code/core/Mage/GoogleAnalytics/Block/Ga.php’. You will want to find the _toHtml() method and look for:

$this->addText('
<!-- BEGIN GOOGLE ANALYTICS CODE -->
<script type="text/javascript">
//<![CDATA[
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/scri$
//]]>
</script>
<script type="text/javascript">
//<![CDATA[
var pageTracker = _gat._getTracker("' . $this->getAccount() . '");
pageTracker._trackPageview("'.$this->getPageName().'");
//]]>
</script>
<!-- END GOOGLE ANALYTICS CODE -->
');

You can update that code to:

$this->addText('

<!-- BEGIN GOOGLE ANALYTICS CODE -->

<script type="text/javascript">

//<![CDATA[

(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\';

(document.getElementsByTagName(\'head\')[0] || document.getElementsByTagName(\'body\')[0]).appendChild(ga);

})();

var _gaq = _gaq || [];

_gaq.push(["_setAccount", "' . $this->getAccount() . '"]);

_gaq.push(["_trackPageview", "'.$this->getPageName().'"]);

//]]>

</script>

<!-- END GOOGLE ANALYTICS CODE -->
');

Change the Location of the Code Snippet on the Page

Once that is updated, you can change the position of the code snippet on the page by modifying the ‘/app/design/frontend/base/default/default/googleanalytics.xml’ file (or in the correct sub-directory for your template if applicable).

Look for the following code:

<reference name="before_body_end">

<block type="googleanalytics/ga" name="google_analytics" as="google_analytics" />

</reference>

and change “before_body_end” to “after_body_start” to move the code snippet to the top of the page.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • LinkedIn
  • Technorati
  • Slashdot
  • Yahoo! Buzz
  • Google Bookmarks
  • Ping.fm
  • Reddit
  • StumbleUpon
  • Suggest to Techmeme via Twitter
  • Twitter

3 Responses to “Adding Google Analytics to Magento and Optimizing Page Speed”

  1. United States of Vitamins Online Says:

    Thanks for these instructions. Very helpful.

    The new code that replaces the old code is missing this at the end:
    ‘);

    And just for reference, on my version of Magento 1.3.3.0, I had to use instead of after_body_start to get the code up in the header.

    Again.. thanks this was just what I was looking for.

  2. United States of Vitamins Online Says:

    it appears that part of my post didn’t show up….

    And just for reference, on my version of Magento 1.3.3.0, I had to use head instead of after_body_start to get the code up in the header.

  3. Geoff Kliza Says:

    Thanks for pointing out that syntax error. The code snippet was fixed.


Leave a Reply