Faster Google Analytics

Google Analytics is a great tool for getting detailed insights on user behavior and traffic on your site.  Normally the standard implementation from Google Analytics works fine but if you’re looking for opportunities for optimizing site speed, the possibility to store the Google Analytics javascript file locally might be something to consider. The main  benefit of hosting the javascript file locally is one less external dependency, and often faster download times.

This guide will teach you how to store the javascript library for Google Analytics locally, and at the same time build a php script that automatically keeps the javascript library up-to-date, so there isn’t any manually maintenance required.

If you think this guide is too complicated you might want to look at our other Google Analytics post regarding asynchronous loading

Local hosting of ga.js

In the normal installation of Google Analytics, you just have to paste the code below into your site,  just above the </body> part of the html.

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

If you want to host the main javascript library for Google Analytics locally, point your browser to the address of the ga.js file at Google and download the file as a text file named local-ga.js.

Then upload the file to your own server eg. in the folder “http://www.example.com/static”

Last but not least you should modify your Google Analytics tracking code to point to the local file, instead of the file hosted at Google:

<script   type="text/javascript">
  var gaJsHost = (("https:" == document.location.protocol) ?   "https://ssl." : "http://www.");
  document.write(unescape("%3Cscript src='" + gaJsHost +   "<strong>example.com/static/local-ga.js</strong>' 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>

And voila – now your Google Analytics javascript is served from your own server. It’s always a good idea to check your  Google Analytics account to see if everything is working fine with the local file.

However there is one important thing to notice – If Google changes the original ga.js file – and that happens from time to time, there is a risk that Google Analytics won’t track your traffic correct. Therefore you should download a fresh ga.js from Google on a regular basis.

Download script

I’m not a big fan of doing things manually if they can be done automatically, so my strong recommendation is to create a script that can download the ga.js file from Google, and update the local file on your site.

The php script below can be used for exactly that job:

<?
// script to update local version of google analytics script

// Remote file to download
$remoteFile = 'http://www.google-analytics.com/ga.js';
$localfile = '/var/www/example.com/static/local-ga.js';

// Connection time out
$connTimeout = 10;
$url = parse_url($remoteFile);
$host = $url['host'];
$path = isset($url['path']) ? $url['path'] : '/';

if (isset($url['query'])) {
  $path .= '?' . $url['query'];
}

$port = isset($url['port']) ? $url['port'] : '80';
$fp = @fsockopen($host, '80', $errno, $errstr, $connTimeout );
if(!$fp){
  // On connection failure return the cached file (if it exist)
  if(file_exists($localFile)){
    readfile($localFile);
  }
} else {
  // Send the header information
  $header = "GET $path HTTP/1.0\r\n";
  $header .= "Host: $host\r\n";
  $header .= "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6\r\n";
  $header .= "Accept: */*\r\n";
  $header .= "Accept-Language: en-us,en;q=0.5\r\n";
  $header .= "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n";
  $header .= "Keep-Alive: 300\r\n";
  $header .= "Connection: keep-alive\r\n";
  $header .= "Referer: http://$host\r\n\r\n";
  fputs($fp, $header);
  $response = '';

  // Get the response from the remote server
  while($line = fread($fp, 4096)){
    $response .= $line;
  }

  // Close the connection
  fclose( $fp );

  // Remove the headers
  $pos = strpos($response, "\r\n\r\n");
  $response = substr($response, $pos + 4);

  // Return the processed response
  echo $response;

  // Save the response to the local file
  if(!file_exists($localFile)){
    // Try to create the file, if doesn't exist
    fopen($localFile, 'w');
  }

  if(is_writable($localFile)) {
    if($fp = fopen($localFile, 'w')){
      fwrite($fp, $response);
      fclose($fp);
    }
  }
}
?>

For the script to work, you need to go through the following steps:

  1. update $localfile to the desired destination and filename of the local Google Analytics javascript file.
  2. make sure that the destination file has the right file permission so it can be overwritten by the script. Chmod 755

Create a cronjob

To make things even easier to maintain, I  recommends that you creates a cron job that automatically executes the above script. If your website host don’t support cron jobs, there are great free sites that offers free cron job services.

We have good experiences with both Cronjob.de (only available in german), cron-job.org (also in german) or if your German isn’t perfect you could also try setcronjobs.com.

There you go – you now have all the benefits of a local javascript file for Google Analytics, and with the help from the download script and the cron job, the solution will maintain itself :-)

Share and Enjoy

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS
fold-left fold-right
About the author
Jørgen Nicolaisen has been passionately interested in everything online since 1995. His experience is based on working with small hobby projects as well as high volume websites. Jørgen is currently focused on the PHP based programming framework - Codeigniter, and WordPress naturally

3 Replies to Faster Google Analytics

  1. ProSpirity says:

    How often would you run the Cron Job? weekly?

  2. jhnidk says:

    From my experience – weekly is fine

  3. Paul says:

    Sweet! I was just thinking about doing something like this the other day, and wondered how it could be done. I can also apply the same technique with other files from other sites in the same manner.

    Thanks for the solution.

Comments are now closed for this article.