Leverage Browser Cache Optimize Google Analytics

Is Google Slowing you down?

How do you leverage browser cache for Google analytics. Since Google added page load times to its ranking system I find it quite ironic that googlies analytic code slows your site down. So the question is, what can we do about it?

Well Google did add asynchronous loading to it’s coding which has helped a little but we want it to be faster.

The short answer is to host it on your own server and download the latest script from Google daily. This way you get cache the java script as well as cache it.

Sounds like a plan right?

So I began my mission to find a solution, as I am not that good at creating what is called cron I decided to do what anyone else would do, GOOGLE it.

Hours later I found what I was looking for, trust me it was not easy to find, but through a combination of sources I had all that was needed to implement the plan.

Google Analytics shall be tamed

I will guide you though the process step by step and explain as I go.

First you need the Google analytics code which you can get by typing google-analytics.com/ga.js be aware this is a monster script and you can see why it slows your site down right.

Secondly you will need to create a file on your hosting account, create the file in the root folder of your domain. Same place as wp-config, wp-content, wp-admin etc. Call it whatever you like as long as it ends with .js in my case I just called it ga.js If you right click and view source of my site, scroll to the bottom you can see the code there.

Next, copy all that information from the Google analytics link above, just press (control A) and save it inside the file you just created on your hosting account. You can do that via FTP or through Cpanel, Godaddy file manager and whatever other set up hosting companies use.

So that’s the first part out of the way, whats next…

Now that we have the script on our hosting account, we need to make sure it works.

Grab you Google analytics script which would look like this:

<script type="text/javascript">
  var _gaq = _gaq ¦¦ [];
  _gaq.push(['_setAccount', 'UA-XXXXXXXX-X']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);

Look near the bottom where it says ‘.google-analytics.com/ga.js’; change it to yourdomain.com/ga.js or whatever you called your script. Then it would look something like this

<script type="text/javascript">
  var _gaq = _gaq ¦¦ [];
  _gaq.push(['_setAccount', 'UA-XXXXXXX-X']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.diywpblog.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);

Refresh your page when complete and right click to view you source and scroll to your google analytics code to make sure it is there. Also enter your google analytics code in to your browser and it should load the same content as the analytics link above. If it looks like a monster then your good to go.

How do we update the script

There are two options here, the first is you could copy the google analytics script by typing in google-analytics.com/ga.js and copy its content each day to make sure your up to date, or we can employ the powers of cron.

What is cron?

Cron is in simple terms a way of executing commands or scripts on a daily, weekly, monthly, yearly basics to perform automated tasks. What we want to do is set up an automated task to download Google analytics java script each day to make sure it is up to date.

Create another file and call it something like ga-cron.php and save it to the same place you saved the Google analytics code which should be your root folder. Then copy this code in to the folder and save. You will only need to make one change, Where is says Insert absolute path to the file here.

Usually the absolute path can be found on your dashboard but to quickly find it if its not clearly stated is to enter your domain in to that line followed by the ga.js or whatever name you used for you Google analytics script. Then run this script by typing in your browser, http://Your-domain-name.com/ga-cron.php When you do this the script will execute, but there will be errors, one of them will be about using http. Copy the bold error because that contains your absolute path and change it as necessary.

Once you can run the script with out error then your good to move on to the final part.

Note: for the ga.js file make it writable.

// script to update local version of Google analytics script

// Remote file to download
$remoteFile = 'http://www.google-analytics.com/ga.js';
//For Cpanel it will be /home/USERNAME/public_html/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 );
  // On connection failure return the cached file (if it exist)
} 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: Gecko/20070725 Firefox/\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
    // Try to create the file, if doesn't exist
    fopen($localfile, 'w');

  if(is_writable($localfile)) {
    if($fp = fopen($localfile, 'w')){
      fwrite($fp, $response);

Finally we need to set up the cron

The cron is simply gonna execute the php code above.

For Godaddy you can do this by going to content—> cron job manager.

Select create cron: give it a name: select update frequency.

I set mine to every hour, but you can do it once a day or once a week, its up to you.

Where it says command, don’t type anything in there, just select browse and select the php file you created then save.


For Cpanel select cron jobs.

Select common settings to set a frequency.

Then you need to type the command which should be something like

php /home/username/public_html/ga-cron.php

Fill in the appropriate information.

General points

I would run the cron at 5 minute intervals at first and check the modification time of the Google script which you have on your server, if it changes by itself then you are good to go.

If you have any questions then send me an email via the contact page or by leaving a comment below.

Don’t forget to sign up for all the latest optimization tips.

I would like to thank Jørgen Nicolaisen for the script although the explanation wasn’t simple enough.

Meet the Author

Matthew Horne

Matthew Horne is web developer who specializes in optimized development. He also builds custom solutions instead of reverting to plugins. Matthew Has a strong understanding of PHP, JavaScript, jQuery.

44 comments… add one
  • Philip Blomsterberg Nov 10, 2014, 10:31 pm

    Thx a big bunch Matthew. I have been getting suggestions about this in Pingdom etc and had no idea how to fix. Cheers

  • Jason Doyle Nov 29, 2014, 3:33 pm

    Thanks Matthew, This worked a treat

  • Marisa Jan 30, 2015, 8:29 am

    Hi Matthew

    I thought I did this all correctly but when I test the site in pagespeed insights it still says I need to leverage browser caching for google analytics.

    Maybe my file isn’t writable?

    “Note: for the ga.js file make it writable.”

    How do I ensure that it is?


    • Matthew Horne Feb 9, 2015, 5:32 am

      Marisa, caching can only be set by the server the resource is sent from, so in your case, resources that come from an external source and don’t have caching set will still be flagged.

  • John Feb 2, 2015, 4:48 pm

    the code is changed from when you wrote the article. it is not the same.

  • phponwebsites Feb 11, 2015, 10:19 am

    Thanks. Very useful content..

  • Carsten Hoppe Feb 12, 2015, 6:43 pm

    all done, but analytics is not counting since yesterday. Cronjob is working well. Ideas?

    • Matthew Horne Feb 24, 2015, 4:13 am

      I believe that Google has updated its code. I haven’t checked just yet.

  • Lochlann Feb 23, 2015, 11:26 pm

    I followed this tutorial **Thanks ever so greatly, btw** However when I run the .php it just returns a blank white screen. Not sure what I did wrong..

    • Matthew Horne Feb 24, 2015, 4:26 am

      The php file isn’t intended to return anything, its intended to write to another file.

Leave a Comment