To save some milliseconds I’ve been sparing my visitors a DNS lookup by fetching the ga.js file, on which Google Analytics is dependent. I host and serve the file locally, and I run a daily cron job to execute a script that downloads the latest ga.js file from Google so that if they update it somehow I have a fresh copy. That and other handy things were made by Mr. Charles Torvalds (website, G+).

Google Analytics is now migrating to Universal analytics (google it if you’re interested, and follow Google’s steps to switch to the new system before proceeding here). Let me now try to be the first to attempt to offer you the instructions I had used (crediting Charles Torvalds one more time, all I did was tweak his code a bit) to host Google’s javascript locally, though revised slightly for the new Analytics javascript file and code snippet. Though if this stuff below looks too complicated for you to bother, I do recommend that you go into Google Analytics and switch yourself to this new Universal rig.

1) Updating script, cron job:
In your document root, make a directory (/var/www/yourwebroot/ga/ for example) where the .js will be stored. Create a script, call it analyticsupdate.sh, put it in /usr/bin/ (or wherever) with the following (but modified for your own configuration):

/bin/sh

# TMP DIRECTORY
MYTMP=/tmp/

# SAVE analytics.js HERE
INSTALL_IN=/var/www/yourwebroot/

# RESOURCE URLS
GOOGLE_GA_URL=http://www.google-analytics.com/analytics.js

# USER-AGENT
UA="Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36"

# CD TO TMP DIRECTORY
cd $MYTMP

# DOWNLOAD THE FILE
curl --header "Pragma:" -f -s -A "${UA}" -m 1800 --retry 15 --retry-delay 15 --max-redirs 8 -O $GOOGLE_GA_URL

# GIVE FILE CORRECT PERMISSIONS
chmod 644 $MYTMP/analytics.js

# COPY FILE TO SITE DIRECTORY
cp -r $MYTMP/analytics.js $INSTALL_IN

# RETURN TO OLDPWD
cd $OLDPWD

exit 0;

 

Save and chmod the script +x, then test the script (there should be no terminal output), make sure it drops an analytics.js in your /webroot/ga/ directory, should be roughly 30KB. Make sure the file is readable from the web, and if not, chmod / umask accordingly and check again. If it works, add this line to cron:

@daily /usr/bin/analyticsupdate.sh >/dev/null 2>&1

 

2) Your site’s global header
Now, in your site’s header file, back up your existing header, then edit your live header, comment out your existing Google Analytics script and lay this in, substituting the Xs with your site’s GA profile and your domain in the two spots:

<!--  LOCAL GOOGLE UNIVERSAL ANALYTICS JS -->
<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//yourdomain.com/ga/analytics.js','ga');
  ga('create', 'UA-XXXXXX-X', 'yourdomain.com');
  ga('send', 'pageview');
</script>
  <!-- END LOCAL GOOGLE UNIVERSAL ANALYTICS JS -->

3) Check again that it’s working.
Save, clear cache if needed and watch your Google Analytics live feed to see if it appears to work or if your traffic drops off over the next half hour. The next day, check your Google Analytics to make sure the data seems to exist, check your webroot/ga/ directory to see that your script worked and that your analytics.js file has a fresher timestamp. If it does, maybe remove the old Analytics code you commented out and enjoy your saved DNS lookup plus whatever this Google Universal Analytics thing is. By the way, for you RSS junkies, here’s a good one to add.

Doug Simmons

5 COMMENTS

  1. hi, i’m on the sharing host with apache web server can you explain how can i do this on my blog please?

    thank you.

  2. Hamed: Since you’re on shared hosting and therefore don’t have root or access to cron, this may not be worth it to you as Google routinely modifies the javascript file to improve Analytics, so not being able to schedule a daily script to fetch a fresh copy, you’d have to update it manually. Or just let it get stale.

    But the procedure, depending on your shared hosting rig, is to download a copy of analytics.js from the url in the script, upload it somewhere in your web root, edit your theme’s header.php with the snippet above, removing or commenting out the existing snippet, and see if it works and if it improved the speed.

  3. i have access to do cronjob with just php.
    can you help me to do that with php?
    thank you for your respond

  4. If you can make a cronjob then first put that script on your server somehow, make it executable, test it to see if it downloads the latest GA script in the directory you specify, then schedule cron to execute the update script daily. Once you think that’s working, then try replacing the header snippets.

  5. Hamed, note that this does only three things, and most people in your position wouldn’t care about any of them:

    Nerd value and a learning experience, saving your visitors one UDP DNS resolution they may already have cached and a TCP handshake to another host when they are already connected to you, and you remove a third party, whoever they’re using for DNS, from knowing that they visited a website with Google Analytics.

    To see if this is worth your while performance-wise, using Chrome – inspect element – network, or YSlow, clock a few /uncached/ page loads of the front of the site and see if there are other things you could do that would be easier and would shave off much more time than this local hosting. Perhaps your server is slow or located far away from the bulk of your audience, then Google might fire over the javascript faster in spite if the extra steps.

    If your interest is the nerd value and learning, by all means proceed but if that grabs you, might I suggest moving your site from a shared hosting rig to an unmanaged VPS? That’s how to make it interesting..

Comments are closed.