search ]

Load Google Analytics Locally from your Own Server

When you optimize the number of server requests (HTTP Requests), you will likely encounter the Google Analytics script at some stage. This script makes an asynchronous request to download the analytics.js file from Google’s servers.

Since this is an asynchronous request, it does not block or stop the loading of other scripts and does not interfere with the rendering of the DOM. However, it involves an additional DNS Lookup and Round Trip Time. Moreover, you are dependent on Google’s servers over which you have no control.

So, in order to avoid this situation, improve the site loading time (even if by 0.000001 seconds), and enhance your scores by a few points, you might want to load the Google Analytics script locally from your own server.

Lighthouse recommendation regarding Leverage Browser Caching of analytics.js

Lighthouse recommendation regarding Leverage Browser Caching of analytics.js

GTmetrix recommendation regarding Leverage Browser Caching of analytics.js

GTmetrix recommendation regarding Leverage Browser Caching of analytics.js

The idea is very similar to locally loading Google Fonts to improve loading time, gain control over the files, and avoid the “Leverage Browser Caching” note in various speed testing tools.

However, unlike fonts that do not update often, the Google Analytics script is updated frequently, and therefore Google does not recommend doing this, but we will make the change because there is a solution…

In this post, we will see how to load the Analytics script locally from your server and how to create a Cron Job via cPanel that will automatically update this script once a day, thus solving the update issue.

We should mention now that the improvement in loading time will be negligible if at all. The action is mainly performed to eliminate this note in the speed testing tools. It’s up to you whether to implement it or not. By the way, there are plugins like LiteSpeed Cache that allow performing a similar action through the plugin’s management interface.

Local Loading of Google Analytics for Website Speed

Let’s get to it. These are the steps to load Google Analytics locally from your server:

Let’s get to it. Here are the steps to locally load Google Analytics from your server:

1. Click on the following link https://www.google-analytics.com/analytics.js.

2. Copy all the code that appears in this link (the analytics.js file).

3. Create a file named local-ga.js and paste the code you copied into it.

Loading Google Analytics Locally

4. Upload this file to your server via FTP, for example to the folder /public_html/local-ga.js.

5. Replace the Analytics tracking code with the 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.co.il/local-ga.js','ga');

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

</script>

Note that you need to edit https://example.co.il/local-ga.js according to your domain and of course change the tracking ID accordingly (UA-xxxxxxx-x).

6. As mentioned, Google updates the analytics.js file frequently. We can embed these updates on our server automatically by creating a file named ga-update.php for this purpose. Create an empty file by this name and copy the following code into it:

<?php

$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);
        }
    }
}
?>

Do not forget to edit /home/username/public_html/local-ga.js according to the location where you placed the local-ga.js file.

7. Upload this file you created to the public_html folder.

8. Last step – In this step, we will create a Cron Job using cPanel.

  • Log into cPanel and click on Cron Jobs.
  • Change — Common Settings — to Once Per Day and add the following code to the command field:
/usr/bin/php /home/username/public_html/ga-update.php >/dev/null 2>&1

Don’t forget to change the location /home/username/public_html/ga-update.php/ accordingly.

Click the Add New Cron Job button and you are done.

Updating Analytics with Cron Job in cPanel

So, do you see an improvement in the score?

Although the score you receive from speed testing tools depends on many factors beyond your website and server, still – one error will disappear from those tools, an error related to Leverage Browser Caching.

Here is a test I conducted on Savvy Blog before and after implementing Google Analytics locally on the server:

Before local implementation of Google Analytics

Before local implementation of Google Analytics

After local implementation of Google Analytics

After local implementation of Google Analytics

It is recommended to use the WebPageTest tool for actual website speed testing over other tools.

How to Load Analytics Locally on WordPress Sites?

If you are using WordPress to implement Google Analytics there is no need for any additional or special action. This method can be implemented because there is no actual difference – the script loading Analytics is the same across all sites.

However, if you do not feel comfortable performing these actions yourself, you can use a plugin that allows you to do so comfortably. It generates for you the same Cron Job we talked about and also provides several additional options which we will not expand on in this post.

The plugin is called CAOS for Analytics, with over 10,000 downloads and an average rating of 5 stars.

Host Google Analytics Locally

In conclusion

I hope you found this guide useful and that it has helped you understand how to implement Google Analytics on your site without affecting your speed score in Google Pagespeed Insights, GTmetrix, Lighthouse, and the like.

By the way, without implementing this method, and if you are using Google Analytics of course – you will not be able to achieve a score of 100 in Google’s speed testing tools, but remember that it is just a score and not a measure of the actual speed of the site.

Anyway, if you know another way to locally implement Analytics, whether in WordPress or not, we would be happy if you share it with us in the comments of the article… Good luck! 🙂

Roee Yossef
Roee Yossef

I develop custom WordPress themes by design. I love typography, colors & everything between, and aim to provide high performance, seo optimized websites with a clean & semantic code.

0 Comments...

Leave a Comment

Add code using the buttons below. For example, to add PHP click the PHP button & add the code inside the shortcode. Typo? Please let us know...