Published Thursday 14 September 2017
Categories: General |

Share this Share on Facebook Share on Twitter Share on Google Plus
Post View Counter 321

Google Analytics PageSpeed fix

We test websites using tools such as Google PageSpeed Insights or GTmetrix to check the speed of their websites and find any potential issues with the content or other issues.

One problem we often find about regarding the Google PageSpeed Insights site is and error for “Leverage browser caching” which is reported for Googles own analytics scripts which are hosted at http://www.google-analytics.com/analytics.js
This script is used by Google Analytics to track website visitors but always seems to flag up as a problem for their own website testing tools.

The error message returned for this issue is:

Google Analytics PageSpeed fix

A workaround for this is to have the analytics.js file hosted within the clients website but as the Google Analytics system is often updated the analytics.js file can easily go out of date and not have the latest functionality.

One solution would be for the clients to manually update their websites daily with the latest version of the file or another way which we use would be to use the Windows task scheduler to run a basic application to download the file each day and copy it into each website which uses the local tracking file.

The code below is from a simple console .NET application we wrote using Visual Studio to download the analytics.js file from Google each day and copy it into the websites javascript folders.

using System;
using System.Net;


namespace ApexGetAnalyticsScript
{
    class Program
    {
        static void Main(string[] args)
        {
            string remotefile = "https://www.google-analytics.com/analytics.js";

            try
            {
				// download file from google and save to local folder
                WebClient webClient = new WebClient();
                webClient.DownloadFile(remotefile, @"C:\website1\wwwroot\js\analytics.js");
            }
            catch { }
            try
            {
            	// copy new file to other websites as required
                System.IO.File.Copy(@"C:\website1\wwwroot\js\analytics.js",  @"C:\website2\wwwroot\js\analytics.js", true);
                System.IO.File.Copy(@"C:\website1\wwwroot\js\analytics.js",  @"C:\website3\wwwroot\js\analytics.js", true);
            }
            catch { }
        }
    }
}

With the Google tracking code located locally on each website, the online site checkers no longer show the “Leverage browser caching” error messages.

Permalink