Using Google Analytics Locally to Improve Page Speed Score

#1

Hi,

I’m using Google Analytics locally to improve page speed scores of my website.
It fixes Leverage Browser Caching error on Pagespeed Insight and also without using plugin.

  1. Click https://www.google-analytics.com/analytics.js

  2. Copy all codes on analytics.js

  3. Create a local-ga.js file and paste analytics.js codes you copied.
    local-ga-js

  4. Upload local-ga.js file to the FTP. Example: /public_html/local-ga.js

  5. Change your old Google Analytics tracking code with following code:


<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','https://example.com/local-ga.js','ga');

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

</script>

:point_right: Don’t forget to edit https://example.com/local-ga.js and UA-xxxxxxx-x according to your tracking id.

  1. Google always edits analytics.js codes and we can implement this changes automatically on our server by creating ga-update.php file. Create an empty ga-update.php file, paste following code on your ga-update.php file:

<?
$remoteFile = 'https://www.google-analytics.com/analytics.js';
$localfile  = '/home/username/public_html/local-ga.js';

$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) {
    if (file_exists($localfile)) {
        readfile($localfile);
    }
} else {
    $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 = '';
    while ($line = fread($fp, 4096)) {
        $response .= $line;
    }
    fclose($fp);
    $pos      = strpos($response, "\r\n\r\n");
    $response = substr($response, $pos + 4);
    echo $response;
    if (!file_exists($localfile)) {
        fopen($localfile, 'w');
    }
    if (is_writable($localfile)) {
        if ($fp = fopen($localfile, 'w')) {
            fwrite($fp, $response);
            fclose($fp);
        }
    }
}
?>

:point_right: Don’t forget to edit /home/username/public_html/local-ga.js according to your local-ga.js file. And upload your ga-update.php to your public_html folder.

  1. Last step, we will create a cron job by using cPanel.
  • login your cPanel and click cron jobs
  • your will see “add a cron job” field in the cron jobs page
  • change the ‘‘common settings’’ as a ‘‘once a day’’
  • add the following code to ‘‘command’’ field

/usr/bin/php /home/username/public_html/ga-update.php >/dev/null 2>&1

:point_right: Don’t forget to change /home/username/public_html/ga-update.php

  • and click Add New Cron Job button.

Done!

My English language is not good. Sorry about it :frowning:

Edit by Mod: Preformatted.

11 Likes
#2

Don’t ever do that!

Simply said, Google updates tracking code every few days and they keep the file (analytics.js) same. you make a local copy, you lose on updates and probably after a few days, google will stop listening to your local copy as well.

#3

There are a lot of versions of tracking code bro.
When people put their tracking code to their header, they never change it.
Because nobody check it whether tracking code was changed or didn’t.

#4

That is the reason why google commits changes to their own js files instead of asking people to change their tracking code everytime.

#5

May be you’re right. But There is a plugin for this option.

A cool plugin created by Daan van den Bergh that enables you to complete optimize the usage of Google Analytics on your WordPress Website. Host your Google Analytics javascript-file (analytics.js) locally and keep it updated using wp_cron(). Easily Anonymize the IP-address of your visitors.

#6

Do You read this? Do You?

#7

Exactly! We made this without using plugin.

#8

I highly doubt that script will work!

#9

I have been using it for 2 months. It still works well.
Cron jobs update local analytics.js everyday.

1 Like
#10

I’d still ask again! what is the obvious advantage to do so much just to host 1 file locally?

I would much rather not bother doing all this and if I’m too lazy I’ll set cloudflare to automatically inject google analytics code.

#11

It is a way of optimization methods.
You already know; there are a lot of ways for optimizing page speed.
just part of these methods.

#12

I don’t use any kind of tracking so it is not related to me

#14

Thank you for your suggestion brother. You’re right! The best optimization type is always image optimization. I just wanted to reach 100/100 point in Google Page Speed Insight and I did and shared it :slight_smile: Thats all…

1 Like
#15

Hosting Analytics locally definitely has a impact on load time.

2 Likes
#16

NOTICE: I have been using Google Analytics locally on my blog for 3 months. And I have checked it is working or not working via https://seositecheckup.com/tools/google-analytics-test

Looks good and updated automatically!

2 Likes
#17

@Turk Good to see, using local analytics helps in reducing the one request.

2 Likes
#18

please tell how to check that my analytic.js is updating or not. Means I install gp-update.php properly or not

#19

With last modified header response.

#20

when I open website.com/ga-update.php it contain same code as analytic with last few line missing in it. is it ok?

#21

Difficult to say without checking manually. :confused: