Jump to content
  • Checkout
  • Login
  • Get in touch

osCommerce

The e-commerce.

Leverage browser cache optimise Google Analytics


Hotclutch

Recommended Posts

Source: http://diywpblog.com/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']);
_gaq.push(['_trackPageview']);

(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);
})();
</script>

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']);
_gaq.push(['_trackPageview']);

(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);
})();
</script>

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.phpWhen 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';
$localfile = 'ENTER YOUR ABSOLUTE PATH TO THE FILE HERE';
//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 );
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);
}
}
}
?>

Link to comment
Share on other sites

Here are 3 times before the change is made (Store page parse time set to true in Admin):

 

0.377s
0.083s
0.098s
 
And 3 times after the change is made.
 
0.087s
0.083s
0.081s
 
You do gain about 1 point on Page speed results in webmaster tools.
 
The only down side of this that i can think is that there may be a short period of time where the ga.js script is out of date (before cron updates) if Google makes a change on their side.
Link to comment
Share on other sites

If anybody has difficulty in determining their absolute path, then create a php file called findpath.php with the following contents:

 

<?php
echo __FILE__;
?>
 
Upload to your server root, and then call in your browser. The absolute path will be the part echoed before findpath.php. Delete when done.
Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...