Host Google Analytics js file locally with auto update

Category : WordPress

Google Analytics help you make data-driven decisions by showing you the stats that matter. It shows how the users of the website interact with the website’s content. It shows what per cent of the user clicked on which link on the website and much more. Google Analytics js fetch request is marked as an external request which will be shown in many only PageSpeed Test like GTMetrix, Pingdom, etc. You will notice the following message:

Leverage browser caching for the following cacheable resources:

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

In this guide, we will locally host javascript and minimize external requests or minimize DNS requests which will eventually enable analytics js for Leverage Browser Caching in order to increase the speed and the score of your site in GTmetrix.

Requirements

  1. FTP or cPanel File Manager Access
  2. Setting cronjob permissions

Procedure

Create a Google Analytics js in your website directory.

  1. Login to cPanel File Manager or FTP.
  2. Open https://www.google-analytics.com/analytics.js URL and copy all the content followed by creating analytics.js in your website directory.
  3. Save the analytics.js after pasting the entire copied code.

Add Google Analytics code to the website

  1. Login to cPanel File Manager or FTP.
  2. Edit the header.php of your active theme or child-theme on the website and add the following code in the bottom.

    (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://www.yoursite.com/analytics.js‘,’
    __gaTracker’);
    __gaTracker(‘create’, ‘UA-XXXXXXXX-X‘, ‘auto’);
    __gaTracker(‘set’, ‘forceSSL’, true); __gaTracker(‘send’,’pageview’);

    Replace the URL and GA Tracking ID in the above code accordingly.

  3. Save the file after doing the required changes.

Note: There are chances if the theme is updated then don’t forget to cross-check the GA Code in header.php file.

Google can make changes to their analytics.js file and you will have to update the locally hosted analytics manually. If you want to discard manual updating then you can follow the next part of the guide which will update local file automatically.

 

How to automate updating of local analytics.js file using cron job on the server. (Optional)

This is an optional part of the guide for advanced level users who want to automate the updating of local analytics.js file.

Create a PHP Script that will be used by cron to update local js file.

Open cPanel File Manager or FTP and create a ga-update.php file in the root directory of the website and paste the following content.

<?php

$remoteFile = ‘https://www.google-analytics.com/analytics.js’;

$localFile = ‘/home/user/public_html/analytics.js’;

// Check if directory exists, otherwise create it.

$uploadDir = ‘/home/user/public_html/’;

if (!file_exists($uploadDir)) {

wp_mkdir_p($uploadDir);

}

// 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, $port, $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);

}

}

}

?>

 

Following values need to be adjusted in the above script. Same values are highlighted in the script.

$remoteFile: the source of the script file you want to download,
$localFile: the path to where you want to save the file — including filename,
$uploadDir: the path to where you want to save the file, without the filename.

Creating a Cron job to run the script at a specific interval which can be every 12 hours or 24 hours.

  1. Login to cPanel or User in which website is hosted.
  2. Add the following cronjob to run the script every day at 12:30 am

    30 12 * * * /usr/bin/php -f /path/to/your/ga-update.php >/dev/null 2>&1

    Here /path/to/your/ga-update.php is the full path of the script created in the last step.

  3. Save the cronjob.

We hope this guide did help you understand how to add Google Analytics to WordPress without sacrificing your PageSpeed score and website performance by leverage browser caching Google Analytics.