Leverage Browser Caching for Google Analytics

0 74

How to Leverage Browser Caching for Google Analytics Javascript & Make the Code even Better by Adding Support for Preloading of Javascript in HTML5 Way

This website doesn’t use Google Analytics or any social widgets + Social Javascript, this was an implement I made to speed up websites of my clients

When it comes to being a webmaster or blogger speed does matter, every millisecond counts and converts into valuable conversion, Google PageSpeed Insight & Pingdom are best way to monitor your website’s performance.

Pagespeed insight gives details on your pages to improve Page Speed, Leverage browser caching plays major role in all websites because it forces the browser to load the cached file instead of trying to fetch it from the web server so it reduces the wastage of Bandwidth. By configuring “Leverage browser caching” server load can be reduced ultimately also users will see faster pages.

Google analytics is a great and free service by Google (sure there is a premium paid version available but If you’re a small sized publisher Free version is definitely enough for you)
Google Analytics is a Free web analytics service by Google that tracks and reports website traffic with the help of Javascript

Google Analytics Leverage Browser Caching

That’s really good to hear but do you know Google Analytics javascript lives in cache only for (www.google-analytics.com/analytics.js) 2 hours? you can not add or change expires headers to external files

browser caching http //www.google-analytics.com/analytics.js (2 hours)

When you look at the Change log of Google Analytics it changes less frequently so caching it for at least two weeks would be a Good idea, isn’t it?


analytics.js file will be freshly updated twice a day automatically on your server; new file will be served after the update, but file will have a cache life time when you serve through your domain with proper htaccess cache-control

Adding a Cron Job to Fetch and Host analytics.js in Your Hosting

This is the tricky part, here you are going to add a cron job which will download analytics.js file from (www.google-analytics.com/analytics.js) Google and host it locally on your hosting, the usage of cron is to make analytics.js updated

The following steps must be completed through FTP or File Manager of your Hosting Control Panel

Create a folder named ‘ga’ in your public_html folder, open it

Create a file named ‘analytics.php’, with the following content and upload it to ‘ga’ folder or you can download it Here

Set a cron job with Cpanel

// script to update local version of Google analytics script

// Remote file to download
$remoteFile = 'https://www.google-analytics.com/analytics.js';
$localfile = getcwd() . '/analytics.js';
//For Cpanel it will be /home/USERNAME/public_html/ga/analytics.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.0rn";
 $header .= "Host: $hostrn";
 $header .= "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv: Gecko/20070725 Firefox/";
 $header .= "Accept: */*rn";
 $header .= "Accept-Language: en-us,en;q=0.5rn";
 $header .= "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7rn";
 $header .= "Keep-Alive: 300rn";
 $header .= "Connection: keep-alivern";
 $header .= "Referer: https://$hostrnrn";
 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, "rnrn");
 $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);

Set a cron job with cPanel but first, you need to know the Home directory path, you can find it in the main cPanel menu see the following Image

find home directory cPanel

According to the image above path to Home directory, is /home/USERNAME/ the location path of your analytics.php would be /home/USERNAME/public_html/ga/analytics.php

Set a cron job to run that php twice a day

cron command is php /home/USERNAME/public_html/ga/analytics.php final cron job will look like the following image

add a cron job google analytics


Leverage Browser Caching for Google Analytics

Add this code to End of your .htaccess just before mod_deflate (if you have mod_deflate section), this ensures your hosted analytics will remain in browser cache for two weeks

<IfModule mod_expires.c>
          <FilesMatch ".(jpe?g|png|gif|js|css)$">
                      ExpiresActive On
                      ExpiresDefault "access plus 2 week"

If you want to leverage browser caching for Google Analytics Script then its very easy like modifying the code a little,  after setting up Cron Job, use the following code instead of the analytics code provided by Google
Just Replace XXXXX-Y with your Google analytics tracking ID, replace www.yourwebsite.com with your domain name

<!-- Google Analytics -->
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
})(window,document,'script','https://www.yourwebsite.com/ga/analytics.js','ga');ga('create', 'UA-XXXXX-Y', 'auto');
ga('send', 'pageview');
<!-- End Google Analytics -->


Speed Up Google Analytics on Modern Browsers

The above code loads javascript asynchronously and works on all browsers without hassle but modern browsers can preload asynchronous scripts and cache them if they are loaded in html5 way

<script async src='https://www.example.com/ga/analytics.js'></script>

preloading is not supported on old browsers like IE so analytics will function but a little slower but in all other modern browsers can preload so better shift to latest code which will reduce page load time & nobody is going to use an old browser
don’t forget to replace XXXXX-Y with your Tracking ID

<!-- Google Analytics Modern Way -->
window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
ga('create', 'UA-XXXXX-Y', 'auto');
ga('send', 'pageview');
<script async src='https://www.yourwebsite.com/ga/analytics.js'></script>
<!-- Google Analytics Modern Way -->

Leave A Reply