Optimize Google Analytics

Jun 6, 2016

Optimize Google anylitics

How to leverage browser caching with Google Analytics

Amazing but true when you carry out a Google page speed test you find that Google analytics’s slows your site down, it downgrades your page speed or shows it needs to be fixed as you’re not caching an external resource.

As you cannot cache external resources we need to make them local.

Google has added asynchronous loading to its code but you will still find that this still doesnt cut it if your chasing page speed. The JS file from Google is a massive it really is take a look here  https://google-analytics.com/analytics.js If you create analytics’s now this is the JS you will call, however there is a possibility your code uses ga.js if this is the case you can upgrade or leave AS IS and  reference https://google-analytics.com/ga.js

As we have used the ga.js in our template we will use the for the post, however as stated above you can use either dependant on which you use.

Lets start optimizing Google analytics’s.

Ok firstly you need to know which you are going to use ga.js or analytics.js and take a note of it, you can get the code from your analytics’s dashboard and it will look like this.

[sourcecode language=”plain” highlight=”4,10″]
<script type="text/javascript">

var _gaq = _gaq || [];
_gaq.push([‘_setAccount’, ‘UA-XXXXXXX-XX’]);

(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);


On line 4 your tracking code, if your using a template of some form and the code is already built in its worth adding your tracing code and checking which analytics file its calling before we go to the next stage.

On line 10 is where our code in the template is pointing to google-analytics.com/ga.js

So you have all the info so now we will add a script that will pull the google-analytics.com/ga.js every hour just in case they change the script their end, so this ensures you always have the latest version on your site.

Synchronising the google-analytics.com/ga.js

As stated a few times now this can also be done with google-analytics.com/analytics.js

Create a file called ga.php and upload it above your public_html folder, you don’t need to be accessible via the web. You can also have multiple versions for different sites that your hosting on your cPanel Hosting packages by doing the following ga-site1.php, ga-site2.php etc, ensuring you change each $localfile= address to the different directories

As you see on line 5 below you need to change CPANELUSERNAME to your cPanel Username this will ensure that the file in this case is copied to your cPanel public_html folder. Also the source location needs to be entered in line 4

[sourcecode language=”plain” highlight=”4,5″]

// Remote file to download
$remoteFile = ‘http://www.google-analytics.com/ga.js’;
$localfile = ‘/home/CPANELUSERNAME/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);

Lets automate our script

Ok you need to go to the cron section in cPanel and create a cron job to call our ga.php file in the root directory

[sourcecode language=”plain”]
php -q /home/CPANELUSERNAME/ga-cron.php >/dev/null 2>&1

This will pull the file from Google at the set times you specify, twice daily will be more than enough, however while you’re setting up set to every minute so you know the file has pulled in correctly.

The google ga.js has imported to the public_html

Ok now the file has pulled in to your public_html folder all you need to do is change the code in your site to reflect the changes

[sourcecode language=”plain” highlight=”10″]
<script type="text/javascript">

var _gaq = _gaq || [];
_gaq.push([‘_setAccount’, ‘UA-XXXXXXX-XX’]);

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


Change the code highlighted to reference your site in your template, so in this case we put it in the public_html folder so we have referenced yoursite.com/ga.gs

That’s it the JS file is now local and you don’t have to reference the JS file from Google in real time on every page load.

Video Tutorial


Monthly Archives

Video Tutorials

Follow Us

cPanel Hosting
CloudLinux Hosting
imunify360 protected
Softaculous 1 click installs

Pin It on Pinterest

Share This