A lot of sites, including ours, use Google Analytics to study how people are interacting with the site. It’s overboard for simply measuring visitors, but if you want to track specific conversion goals (like how many new visitors who hit the front page ultimately sign up for an account) it’s great.

One of the problems with it is that it’s not terribly reliable, and because it’s totally JavaScript-based, our end users can see slowdowns if their site is particularly busy. One way to help alleviate this issue is to keep a local copy of their urchin.js file on your server. It will still send stats to Google Analytics, but your end users don’t need to download that file from Google. There are scripts that you can use to download this file nightly, but I wanted a rake task so it would be cross-platform, and have some checks built-in to make sure that we wouldn’t accidentally overwrite the file with bad data if we had a bad download.

This is the script we currently run nightly. Feel free to grab it if you have similar needs:


desc "This task fetches a new copy of urchin.js from google and puts it in place"
task :update_urchin_js do
   require 'open-uri'
   REAL_FILE = RAILS_ROOT + '/public/javascripts/urchin.js'
   TEMP_FILE = REAL_FILE + '.tmp'
      
   #download the updated file to a temp location
   js = open('http://www.google-analytics.com/urchin.js')
        
   #put that download into a temp file
   temp_js   = File.open(TEMP_FILE, File::RDWR|File::CREAT, 0600)
   js.each_line do |line|
      temp_js << line
   end
   temp_js.close
   if File.size(TEMP_FILE) < 1000
      raise "File downloaded from google looks supiciously small: #{TEMP_FILE}"
   end
 
   #make sure the target file exists
   orig_js = File.open(REAL_FILE, File::WRONLY|File::TRUNC|File::CREAT)
   orig_js.close
        
   #copy the temp file to the real file
   FileUtils.copy(TEMP_FILE, REAL_FILE)
        
   #delete the temp file
   File.delete(TEMP_FILE)
end

One Response to “Improve Google Analytics Performance”

  1. My Ghillie » Wishlisting Blog " Blog Archive " Improve Google Analytics Performance Says:

    […] Check it out! While looking through the blogosphere we stumbled on an interesting post today.Here’s a quick excerpt […]

Leave a Reply