cache google analytics banner

How To Cache Google Analytics Code

If you’re trying to increase site speed by caching Google Analytics code then you’re in luck. I’ve created this guide with easy instructions on how to cache your Google Analytics code.

In this guide we’ll be covering the following:

  1. Creating a php script that grabs the Analytics JavaScript from Google server.
  2. Creating a cron job to grab the latest version of the script.
  3. Caching Analytics locally.

We are working with the following:

  1. Host with Cpanel
  2. PHP with Apache
  3. Google Analytics
  4. Full moon

If you don’t have hosting with Cpanel, you’ll have to learn how to add a cron job without Cpanel which is not covered here.

Have your Analytic code handy

First, before we get deep into this, you will need to get your Google Analytics code now if you haven’t already. For this example, we’ll be using the most recent version of the script and it looks like what is followed:

<!-- Google Analytics -->
<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','//www.google-analytics.com/analytics.js','ga');

            ga('create', 'UA-XXXXXXXX-X', 'auto');
            ga('send', 'pageview');

</script>

I recommend starting a rich text document and pasting your GA code into it temporarily for reference later.

Get file from Google

To get the file from Google we’ll create a simple php script. Create a ga-update.php file and copy the following code in and upload to your web host:

<?php

// Full Location To File
$location = '/home/yourhostaccount/public_html/analytics.js';
$analytics = file_get_contents('http://www.google-analytics.com/analytics.js');

file_put_contents($location, $analytics);

?>

What does this file do? It simple grabs the analytics.js file from Google and downloads it to the specified location above.

Change the $location variable to reflect the full path that the Analytic code will be downloaded to. Save. The sample above shows the file, analytics.js , will be saved in the /public_html folder (also known as root).

Setup Cron

Google does update analytics.js now and then. If we don’t get the latest version you may miss out on cool features and updates. So go into your Cpanel account and find “Cron Jobs” under the advanced tab to create a cron.

In the Add a New Crob Job box, select “Once Per Day” in the Common Settings so you don’t have to deal with Minute, Hour, Day, etc.

For Command, you should have something that resembles the following:

/usr/local/cpanel/3rdparty/bin/php /home/yourhostaccoung/public_html/ga-update.php

How your host setup php may be different than what we have so it’s best to ask your host what the correct link is. Note, that there is a space between the two urls. The first url points to php and the second points to ga-update.php that grabs the Analytics code from Google.

Setup .htaccess

Now that you have a file that gets the code and a cron job to make sure it’s up to date, you’ll need to cache your local copy of analytics.js.

Create a .htaccess file in your root folder if you don’t have one yet and add this:

# ----------------------------------------------------------------------
# Expires headers (for better cache control)
# ----------------------------------------------------------------------

# These are pretty far-future expires headers.
# They assume you control versioning with filename-based cache busting
# Additionally, consider that outdated proxies may miscache
#   www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/

# If you don't use filenames to version, lower the CSS  and JS to something like
#   "access plus 1 week" or so.

<IfModule mod_expires.c>
  ExpiresActive on

# Perhaps better to whitelist expires rules? Perhaps.
  ExpiresDefault                          "access plus 1 month"

# cache.appcache needs re-requests in FF 3.6 (thanks Remy ~Introducing HTML5)
  ExpiresByType text/cache-manifest       "access plus 0 seconds"

# Your document html
  ExpiresByType text/html                 "access plus 0 seconds"

# Data
  ExpiresByType text/xml                  "access plus 0 seconds"
  ExpiresByType application/xml           "access plus 0 seconds"
  ExpiresByType application/json          "access plus 0 seconds"

# Feed
  ExpiresByType application/rss+xml       "access plus 1 hour"
  ExpiresByType application/atom+xml      "access plus 1 hour"

# Favicon (cannot be renamed)
  ExpiresByType image/x-icon              "access plus 1 week"

# Media: images, video, audio
  ExpiresByType image/gif                 "access plus 1 month"
  ExpiresByType image/png                 "access plus 1 month"
  ExpiresByType image/jpeg                "access plus 1 month"
  ExpiresByType video/ogg                 "access plus 1 month"
  ExpiresByType audio/ogg                 "access plus 1 month"
  ExpiresByType video/mp4                 "access plus 1 month"
  ExpiresByType video/webm                "access plus 1 month"

# HTC files  (css3pie)
  ExpiresByType text/x-component          "access plus 1 month"

# Webfonts
  ExpiresByType application/x-font-ttf    "access plus 1 month"
  ExpiresByType font/opentype             "access plus 1 month"
  ExpiresByType application/x-font-woff   "access plus 1 month"
  ExpiresByType image/svg+xml             "access plus 1 month"
  ExpiresByType application/vnd.ms-fontobject "access plus 1 month"

# CSS and JavaScript
  ExpiresByType text/css                  "access plus 1 week"
  ExpiresByType application/javascript    "access plus 1 week"

</IfModule>

The above code is taken from the html5 boiler plate .htaccess file and will tell the browser to cache files such as css, js, images, etc. If you don’t want the extra bells and whistles you’ll need the following to cache analytics.js :

# CSS and JavaScript
  ExpiresByType text/css                  "access plus 1 week"
  ExpiresByType application/javascript    "access plus 1 week"

Modify Analytics code

Change your GA code so it points to where your analytics.js is on your web server.

<!-- Google Analytics -->
<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','//www.google-analytics.com/analytics.js','ga');

            ga('create', 'UA-XXXXXXXX-X', 'auto');
            ga('send', 'pageview');

</script>

If your analytic.js is in /public_html then your link should look like www.yourdomain.com/analytics.js .

Now you are able to place GA code at the end of your header or footer as usual.

Conclusion

Why go through all this hassle? Google pushes everyone to leverage browser caching of css, js, and html wherever possible so your site loads faster. I don’t see many sites that implement caching of Google Analytics so this may give you a competitive edge.

We are currently using this on our sister sites and it’s been working great for us. I hope you find this guide useful or informative at least.

6 thoughts on “How To Cache Google Analytics Code

  1. Andrew

    Hi,

    I’ve been using this on my site for the past few months. I’ve been noticing that I’m seeing this warning in google analytics when I view my stats:

    Bad Event Tracking Code
    The Landing Pages report has a (not set) entry. Verify that tracking code for property Damn Fine Shave sends a _trackPageview hit and that it does this before sending any events.

    Any idea how to fix this?

    Thanks,

    Andrew

    Reply
    1. Tan Tuohy Post author

      First make sure that the cron is setup correctly and that it’s actually downloading the Google analytics code to your local server.

      Reply
  2. Moussa

    hi

    i tried to do this. created “ga-update.php” file and upload it “public_html” folder. than created cron job “/home/myaccount/public_html/ga-update.php” but i could not get analytics.js file to public_html folder. where did i wrong. am i need to create js file by my self ? i understood that ga-update.php file downloads js file to public_html folder by it self. can you help me please.
    thanks.

    Reply
  3. Ernesto

    Perfect! Thanks a lot!

    I have tried to solve the Facebook pixel load in the same way but it generates errors. Do you know any way to do it?

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *