Search

Loading Google Analytics Locally from Your Server

When optimizing the number of requests to the server (HTTP Requests), you may encounter a stage in the Google Analytics script. The script makes an asynchronous request to download the analytics.js file from Google’s servers.

Since this is an asynchronous request, it won’t block or stop the loading of other scripts and won’t interfere with rendering the DOM. However, there is an additional DNS Lookup and Round Trip time. Moreover, you depend on Google’s servers over which you have no control.

So, to avoid this situation, improve the website loading time (even if by 0.000001 seconds), and enhance the score you receive in various tools, you might want to consider loading the Google Analytics script locally from your server.


Lighthouse recommendation for Leverage Browser Caching of analytics.js
Lighthouse recommendation for Leverage Browser Caching of analytics.js

GTmetrix recommendation for Leverage Browser Caching of analytics.js
GTmetrix recommendation for Leverage Browser Caching of analytics.js

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

Unlike non-frequently updated fonts, the Google Analytics script is updated frequently, so Google does not recommend this action. However, we will make the change because there is a solution…

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

We note right away that the improvement in loading time will be marginal if at all. The action is mainly taken to eliminate this remark in speed testing tools. It’s up to you whether to perform it or not.

Loading Google Analytics Locally for Website Speed

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

    1. Click on the following link https://www.google-analytics.com/analytics.js.
    2. Copy all the code appearing in this link (the analytics.js file).
    3. Create a file named local-ga.js and paste the copied code into it.

Loading Google Analytics Locally
  1. Upload this file to your server using FTP, for example, to the /public_html/local-ga.js directory.
  2. 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).

  • As mentioned, Google updates the analytics.js file frequently. We can embed these updates on our server automatically by creating an empty file named ga-update.php. 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);
        }
    }
}
?>

Don’t forget to edit /home/username/public_html/local-ga.js according to the location where you placed the local-ga.js file.

  1. Upload the file you created to the public_html directory.
  2. Final step – in this section, we will create a Cron Job using cPanel.
    • Login to 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’re done.


    Updating Analytics with Cron Job in cPanel


So, do you see an improvement in the score?

While the score you get in speed testing tools depends on many factors beyond the website and your server, one error is going to disappear from those tools, an error related to Leverage Browser Caching.

Here’s a test I conducted on Savvy Blog before and after implementing local Google Analytics on the server:


Before implementing local Google Analytics
Before implementing local Google Analytics

After implementing local Google Analytics
After implementing local Google Analytics

It’s worth mentioning that it’s recommended to use WebPageTest tool for checking site speed in practice over other tools.

How to Load Google Analytics Locally on WordPress Sites?

If you are using WordPress to embed Google Analytics, there is no need for any additional or special action. This method can be applied because there is essentially no difference – the script loading Google Analytics is the same script on all sites.

However, if you don’t feel comfortable performing these actions on your own, you can use a plugin that allows you to do this conveniently. It creates the same Cron Job we discussed and provides additional options we won’t elaborate 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 helpful and that you understood how to embed Google Analytics on your site without affecting the speed score in Google Pagespeed Insights, GTmetrix, Lighthouse, and similar tools.

By the way, without implementing this method and if you use Google Analytics, of course, you won’t be able to achieve a score of 100 in Google’s speed testing tools. Still, it’s essential to remember that it’s just a score and not an actual measure of the site’s speed.

In any case, if you know of another way to embed Google Analytics locally, whether in WordPress or not, we’d be happy if you share it with us in the article comments… Good luck! 🙂

Roee Yossef
Roee Yossef

I develop websites & 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

Quick Navigation

Up!
Blog