Cache Google Analytics code

January 17, 2019

As we all chase page speed, we use useful tools out there to understand how we can optimise our websites. Sites like GTmetrics show what changes can be made to improve performance.
What you will find is Google Analytics scripts always showing that improvement is needed through caching,
However as this is an external resource it can’t be cached. The process that follows can also help with other external resources that your website requires; however, you may have to make some changes to plugins/scripts to utilise the local version.
Anything that is pulling files from another site has the potential for latency in the page load, this can also be the case with CDN’s.
If you have a UK website serving UK customers, then a CDN based in the US wouldn’t help your site load quicker, infect it would slow it down. CDN’s are great, but with everything a paid version is the way to go.

Ok let’s get started

So normally you must add the following code or similar in the header of your site, so google can track visitors.
You can see an example below, we have used the following KEYS so its easier to follow and modify.

  • UA-GOOGLETRACKERCODE = Your tracking code goes here
  • www.MYDOMAIN.COM = Your domain name (with or without www. Dependant on your setup)
  • CPANELUSERNAME = Your actual cPanel username.
<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-GOOGLETRACKERCODE', 'auto');
  ga('send', 'pageview');

</script>

As you can see the call to www.google-analytics.com/analytics.js

Revised header code

We will replace with the following once we have completed with the steps below.

<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.MYDOMAIN.com/google/analytics.js','ga');

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

</script>

 

Let’s make the code local

What we need to do is create a process on the server that will get the analytics.js file in this case and copy it to the server, in a place that the site can use.

Create a new PHP file called whatever you want, I am going to call it ga-cron.php
Once you have created the file you need to enter the following code: -

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

// Remote file to download
$remoteFile = 'http://www.google-analytics.com/analytics.js';
$localfile = '/home/CPANELUSERNAME/public_html/google/analytics.js';
//For Cpanel it will be /home/CPANELUSERNAME/public_html/google/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);
    }
  }
}
?>

 

On line 5 you need to set the file you want to copy, line 6 you need to where you want the copy to be saved.

Important to note

The file ga-cron.php has to be in your home directory and possibly in a folder NOT IN THE PUBLIC_HTML FOLDER. The reason for this is this script is pulling in external content, you want control who can use it for security reasons. As its in the Home directory above the public_html folder it cannot be called publicly.

How it works

So as you can see I am pulling the script from https://www.google-analytics.com/analytics.js and then saving to /home/CPANELUSERNAME/public_html/google/analytics.js
When its being saved this does needs to go in the public folder so you can access from the site. As this is the copied google js file there is no issues it being public.

Now let make it copy

Create a cron job with the following command below

php -q /home/CPANELUSERNAME/ga-cron.php >/dev/null 2>&1

 

The following tutorial show you how to make a cron https://www.birchhosting.com/cron-jobs-in-cpanel/
Running the cron once per hour will suffice, as you can see the amount of calls to google will drastically reduce as it will only happen once per hour, not every page load.

Wait for the cron to run and check that the file has appeared in your google folder or whatever you called it.

Home straight

Then all you need to do is change the code in your header

<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.MYDOMAIN.com/google/analytics.js','ga');

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

</script>

 

Hopefully you carried out a test on GTMetrics before you started, test again and you will see that the warnings have gone and better page load times.

This process can be used for any remote files you need to call, always keeping it in sync, just remember to keep the PHP code above the public_html folder.

As always if you need any help, please get in touch.

Monthly Archives

NOMINET Member
cPanel Hosting
CloudLinux Hosting
imunify360 protected
R1SOFT Protected
CloudFlare Enabled
RV Sitebuilder
Softaculous 1 click installs

Pin It on Pinterest

Share This

Share this post with your friends!