drupal google analytics and event tracking

user warning: Table './johnandcailincmsdb/node_counter' is marked as crashed and should be repaired query: SELECT totalcount, daycount, timestamp FROM node_counter WHERE nid = 61 in /var/www/drupal/includes/database.mysql.inc on line 172.

google analytics provides for arbitrary javascript event tracking. anywhere in your page that you can put an onClick or an onMouseOver or any other event you please, you can also name that event and track it in google analytics. this is particularly handy for tracking hits to downloadable content (for example pdf files).

unfortunately, if you use the drupal google analytics module, this functionality will not work.the problem is that for the javascript event tracking to work, the google analytics javascript needs to appear above your event code. however, the google analytics module puts the code in the footer.

here is a simple recipe for modifying the google analytics module to move the google analytics javascript to the top of the page, just after the opening tag.

first, modify the google analytics module so that it does not override hook_footer, and instead just provides a utility method that returns the tracking code. To do this rename the googleanalytics_footer method in googleanalytics.module to googleanalytics_get_tracking_code().

second, add a variable called tracking to the array of variables available to your page template. In your template.php file, add the following blurb to the _phptemplate_variables function.

function _phptemplate_variables($hook, $vars = array()) {
. . .
    if (function_exists("googleanalytics_get_tracking_code")) {
        $vars['tracking'] = googleanalytics_get_tracking_code();
. . .

Finally, print out the tracking code in your page template (page.tpl.php). For example

. . .
<body class="<?php print $body_classes; ?>">
  <?php print $tracking; ?>
. . .

note: moving the google analytics javascript to the top of the page isn't without issues. once you move the code, if google analytics' servers are slow, your site will be too

one way to work around the

one way to work around the issue of a slow or hanging page due to google being slow to deliver the javascript, is to host the javascript yourself and synchronize it with google. this is pretty easy. there is a nice recipe described in this blog.

the latest version of the

the latest version of the google analytics plugin does local caching of urchin.js. this is almost certainly a better option that doing your own javascript caching implementation.

Please note, this entry has been closed to new comments.