How to Leverage Browser Caching for Google Analytics

Cody Schneider8 min read

If you've ever run your site through Google PageSpeed Insights, you’ve probably seen the recommendation to "serve static assets with an efficient cache policy." And right below it, a familiar culprit: a file from Google Analytics like analytics.js or gtag.js. It’s frustrating because the warning comes from Google about their own script, leaving you wondering how you’re supposed to fix something you don't control. This article will show you exactly what this warning means and how to resolve it by hosting your Google Analytics script locally.

GraphedGraphed

Your AI Data Analyst to Create Live Dashboards

Connect your data sources and let AI build beautiful, real-time dashboards for you in seconds.

Watch Graphed demo video

What is Browser Caching?

Before jumping into the solution, it’s important to understand what browser caching actually is. Imagine visiting a website for the first time. Your browser has to download every single piece of that site: the logo, stylesheets (CSS files), images, and scripts like the one for Google Analytics.

Browser caching is like your browser keeping a temporary toolbox of these files. When you visit the site again, instead of re-downloading everything, the browser pulls commonly used files like the logo and stylesheets from its local cache (that toolbox). This makes the page load much faster because it’s not fetching everything from the internet all over again.

This process relies on caching "headers" sent from the web server. These headers tell the browser how long it should keep a file in its cache before checking for a new version. A long cache policy (e.g., one year) is great for site speed, as it minimizes downloads for repeat visitors.

Why Google Analytics Triggers the Caching Warning

Here’s the core of the problem: the Google Analytics script isn't hosted on your server, it's hosted on Google's. You're simply linking to it from your website. Google intentionally sets a very short cache expiration time on their Analytics file - often just two hours.

Why would they do this? It allows them to push updates or changes to the tracking script and ensure that users get the new version quickly, without needing to wait for a long cache period to expire. This gives them control over the script's integrity and features.

This creates a conflict of interest:

  • You and PageSpeed Insights want: A long cache duration to improve your site speed score.
  • Google wants: A short cache duration to maintain control and push updates quickly.

Since you can't log into Google's servers and change their settings, the only solution is to take control of the file yourself.

Free PDF Guide

AI for Data Analysis Crash Course

Learn how to get AI to do data analysis for you — the best tools, prompts, and workflows to go from raw data to insights without writing a single line of code.

The Solution: Host the Google Analytics Script Locally

The most effective way to fix the "leverage browser caching" warning for Google Analytics is to host the script file on your own server. When you host the file locally, you get to set the caching policy. Instead of telling browsers to fetch the script from Google, you'll tell them to fetch a copy from your own domain. This lets you set a long cache expiration period, satisfying page speed tools and making your repeat visitors' experience a little faster.

Here’s a breakdown of how to do this, from the easiest methods to the more manual ones.

Recommended Method for WordPress: Use a Performance Plugin

For WordPress users, the easiest and safest way to host analytics.js locally is with a performance optimization plugin. Many popular plugins offer this feature built-in, automating the entire process for you. They work by downloading the script from Google to your server and then serving it from there. Critically, these plugins also use a scheduled task (a cron job) to automatically check for updates to the script, ensuring your local version never gets stale.

Here are a few plugins that handle this well:

  • Perfmatters: A lightweight performance plugin that provides a simple toggle switch to host your Google Analytics script locally. It works with both standard Analytics and Google Tag Manager.
  • FlyingPress: A comprehensive caching and optimization plugin that includes local hosting of Google Analytics as part of its feature set.
  • WP Rocket: One of the most popular caching plugins for WordPress. Its Google Tracking add-on can host the script locally with the click of a button.

Using a plugin is highly recommended because it manages the crucial step of keeping the script updated. If Google changes the analytics.js file and your local version becomes outdated, your analytics tracking could break. Plugins solve this by auto-syncing the file for you.

GraphedGraphed

Your AI Data Analyst to Create Live Dashboards

Connect your data sources and let AI build beautiful, real-time dashboards for you in seconds.

Watch Graphed demo video

Manual Method (for Non-WordPress or Advanced Users)

If you aren't using WordPress or prefer a manual approach, you can set this up yourself. Be warned: this method requires more technical comfort and, most importantly, creating a system to keep your local script updated.

Step 1: Download the Analytics Script

First, you need to find the full URL of the script your site is using. You can find this by looking at your site's source code. You're looking for one of these:

  • https://www.google-analytics.com/analytics.js
  • https://www.googletagmanager.com/gtag/js?id=YOUR_ID

Copy the URL into your browser, and a wall of code will appear. Save this page as a file named analytics.js or gtag.js on your computer.

Step 2: Upload the Script to Your Server

Using an FTP client or your hosting provider's file manager, upload the script file you just saved to a directory on your server. A common location might be a js folder in your theme or root directory (e.g., /public_html/js/)

Step 3: Update Your Google Analytics Tracking Code

Now you need to edit your website's code to point to the local file instead of Google's server. Find your Google Analytics tracking snippet (it's usually in your website's header file).

Your current snippet for universal analytics probably looks something like this:

(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','//www.google-analytics.com/analytics.js','ga'),

You need to change the source URL from //www.google-analytics.com/analytics.js to the path of your local file. For example:

(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','/js/analytics.js','ga'),

Make sure you have the correct file path. Once saved, your site will load the script from your server, and you can confirm with your browser's developer tools that it's working.

Step 4: Automate Updates (The Critical Step)

This is the most important - and most often forgotten - part of the manual method. You must create a script and a cron job on your server that automatically fetches a fresh copy of analytics.js from Google daily or weekly. Without this, your tracking will eventually break when Google makes updates. A failure here could lead to significant data loss.

Free PDF Guide

AI for Data Analysis Crash Course

Learn how to get AI to do data analysis for you — the best tools, prompts, and workflows to go from raw data to insights without writing a single line of code.

A Note on Google Tag Manager (GTM)

Many sites use Google Tag Manager to deploy Google Analytics. The concept is the same: GTM also loads a script (gtm.js) from Google's servers with a short cache time. Some of the advanced performance plugins mentioned earlier, like Perfmatters, can also host the gtm.js script locally. However, GTM adds another layer of complexity, so tread carefully and test thoroughly to ensure none of your other tags or triggers break after making the changes.

Are There Any Downsides to Local Hosting?

While local hosting solves the caching warning, there are a couple of small trade-offs to consider:

  1. Maintenance Responsibility: You are now responsible for the script. As mentioned, if it isn't updated, your analytics breaks. This is why using a dedicated plugin that automates this is strongly advised over the manual method.
  2. CDN Caching: Google serves its analytics script from a massive, globally distributed Content Delivery Network (CDN). It’s possible a user has visited another website using Google Analytics just before yours, meaning the script is already cached in their browser. By hosting it locally, you forgo this potential benefit. However, the performance gains for repeat visitors to your own site generally outweigh this small loss.

Final Thoughts

That "Leverage Browser Caching" warning from Google's own Analytics script can feel like an impossible riddle, but the solution is clear: host the file on your own server. For most people, a good WordPress performance plugin can handle everything automatically, giving you the site speed benefits without the maintenance headaches. Now you have a direct way to resolve the warning and boost your page speed score.

Improving how you collect your website data is an important step, but the ultimate goal is turning that data into clear, actionable insights for your business. Manually pulling reports and trying to connect the dots between your website traffic, ad campaigns, and sales results can be just as time-consuming as optimizing your site. This is exactly where our tool can help. With Graphed , we connect directly to your Google Analytics, marketing platforms, and sales tools, allowing you to create real-time dashboards and get answers instantly just by asking questions in plain English.

Related Articles