Reduce Unused JavaScript Google Analytics.
Reduce Unused JavaScript Google Analytics. In this post I'll be talking about how to reduce unused JavaScript when using Google Analytics with your WordPress site, why you'd want to do this, and the benefit you'll see by doing so.
This post details how to host Google Analytics or Google Tag Manager locally in your WordPress, how to reduce the size of the Google Analytics Manager tracking JavaScript file and how to optimise the loading of the respective scripts.
If you're looking for more general advice about reducing unused Javascript this is covered in this post.
What is Google Analytics?
Google Analytics is an analysis service provided by Google.
It's designed to track and report traffic on your website, what visitors do on your website, and it also reports information about the visitors themselves such as geographic location and the equipment they're using. It can be customised to report specific tracking events (specific things that visitors do on your website).
The cheif purpose of Google Analytics is to show how visitors interract with your website.
Knowing how visitors use your website and what they do on it allows you to identify the behaviour of visitors, and this information can then be used for things like supplemental marketing activities or provide direction for you with regard to how to improve the experience of people that visit your website.
From a paractical point of view, there's two parts to Google Analytics, and these are:
- The "your website" side of things. This is where the Google Analytics tracking script is embedded.
- The "Google Analytics" account. This is where Google Analytics is configured and where all the reported information is held.
The Google Analytics tracking script.
The Google Analytics tracking script is a JavaScript snippet that's usually embedded in the <head> section of your site. This includes the URL of the JavaScript file, and your Google Analytics tracking ID.
The script itself is effectively what does the tracking, and your Google Analytics tracking ID is also mentioned in the JavaScript snippet. The tracking ID is included to ensure that the data collected from your website is sent to the correct Google Analytics account.
When you set up your Google Analytics account, for the tracking to start you have to add the script to your site. Typically a tracking snippet will look something like this (the GA_MEASUREMENT_ID parts would normally be replaced with your actual tracking ID):
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'GA_MEASUREMENT_ID');
</script>
As you can see there's an external URL in the script:
https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID
From this, we can tell that by using this your site is going to call an additional resource from an external source, and that as it's JavaScript it's going to execute code within the browser. It needs to do this to track what the visitor is doing in their browser when accessing your site.
Google Analytics and the Reduce Unused JavaScript problem.
Imagine you've got your website up and running with all the content and pages in place, and you want to add Google Analytcis to your site.
You set up your Google Analytics account, add the tracking script to your site, and then you check your site using Page Speed Insights (https://pagespeed.web.dev/) and you see that your site's performance metric has decreased and there's now a "Reduce Unused JavaScript" opportunity, and the script that's flagged as problematic is the Google Analytics tracking script.
What you'll see is this:
And if you click the small ˇ at the right hand end of the line, you'll see this:
So you've got Page Speed Insights (provided by google) flagging a JavaScript file (also provided by Google) as problematic.
Whilst this might, at a glance, look like Google complaining about Google this would be a bit of an over simplified way of looking at things.
Some people might write this off as a prolem that they can't do anything about, due to this all being related to the trackign script being provided by google. It's not like you can modify the script now, is it?
But wait... you can!
Addressing the Google Analytics and the Reduce Unused JavaScript problem.
I'll admit that I found this out, in part, by accident.
I'd seen Page Speed Insights reporting what I've mentioned above for my site, and I was looking for a "cheap" way to be able to use Google Analytics. By cheap I mean minimal overhead (so no problems flagged in Page Speed Insights), yet with a level of reporting that allowed Google Analytics to report on the events that I wanted it to.
The main problems as I saw it was that the tracking script was being called from an external source (so there's a DNS overhead when the script is called), and that the tracking script was effectively too big, and not all of it was being used.
My objectives were to host the Google Analytics tracking script locally, and then reduce it's size, or possibly modify it so that it only contained JavaScript that was actually being used. Then see what happened in Page Speed Insights. I mean we are talking about UNUSED JavaScript as being the problem, so I didn't think this was an insane train of thought, and I also wanted to see if this was possible and what the effect would be.
Before you read any further what I'm about to mention is specific to WordPress. If you're using a different CMS, you might be able to do some of this like for like (the Google Analytics account part, you will), but the CMS specific parts, you will have to do differently according to the CMS that you're using.
So let's start with the obvious:
Hosting the Google Analytics Script Locally.
I decided to use the CAOS WordPress plugin to host Google Analytics locally, as it's designed specifically to do this.
Before using this plugin, if you've already added the Google Analytics trackign snippet to your site, you'll need to remove it.
The CAOS plugin is VERY easy to use. You install it and activate just like any other plugin, then go to your plugin list (Plugins > Installed Plugins) and click on "Settings" in the CAOS section:
Then on the "Basic Settings' page:
- Enter your Google Analytics tracking ID in the "Data Stream Measurement ID" field.
- Set the "Tracking Code" to "Asynchronous (default)"
- Click "Save Changes and Update"
Like this:
Before you navigate away from this page, take a look at the part above the settings section, and you should see something like this:
What the CAOS plugin has done, is created a file (in my case 5588d66b.js) that contains the Google Analytics tracking JavaScript, and put it in the local file system of my WordPress (in the wp-content/uploads/caos directory, unless this is explicitly changed in the advanced CAOS plugin settings).
It's then added this local script within the <head> of my site's page output, using the async attribute when doing so.
So I've now got the tracking script hosted locally (rather than calling it from an external source) and by using async, it stops the script being render blocking (as the script is effectively downloaded in the background when page rendering is taking place).
All good so far.
But what about the size?
Reducing the Size of the Google Analytics Script.
You might think that hosting the tracking script locally would allow me to edit it to reduce it's size.
Well, you're not wrong, that is possible, but there are some implications.
- The next time wp_cron runs changes made to the script will be overwritten.
- You'll need to be able to idenfity what is and isn't needed by reading JavaScript.
- You might end up breaking the tracking if you don't edit the file correctly
If you take all of those factors in to account, manually editing the script itself seems less appealing doesn't it?
Also, this JavaScript is coming from somehwere, and the JavaScript does vary in size between sites (if you check them using Page Speed Insights.
By this time, I'd read quite a lot about this porblem and one thing that kept coming up was "overtracking".
Overtracking is when you set up a lot of tracking events in your Google Analytics account. The reason this gets mentioned is because some people will set up tracking events, for events that won't actually take place on their site, as their site doesn't function in a manner specific to the event being tracked.
As I hadn't really set up any specific tracking events in my Google Analytics account, I didn't really think I'd be overtracking on my site, but I thought that it was probably worth validating if I was or not.
To check to see if I was overtracking, in my Google Analytics account I turned off ALL tracking events, then only turned on "Page Views", then saved my changes.
But I'm hosting Google Analytics locally now, so now I need to tell CAOS to get a new copy of the tecking script.
Remember this?:
Clicking the "Regenerate Aliases" link is what tells CAOS to get a new copy of the tracking JavaScript file. This is under Plugins > Installed Plugins > Settings (on the same line as CAOS) and you'll see the above at the top of the page.
Before I clicked "Regenerate Alias(es)" I took a look at the size of the 5588d66b.js file in my hosting, made a note of it, then clicked "Regenerate Alias(es)" and checked the size of the new tracking script file that CAOS had generated.
It was indeed smaller.
There's a direct relationship between the tracking events set up in your Google Analytics account, and the size of the tracking script. The more tracking events you have, the larger the script.
The tracking events that are set up in Google Analytics by default contribute to the size of this script, and the default racking events may actually be more than you need so you may have to turn off some of the default tracking events to reduce the size of the tracking script.
Unfortunately I can't tell you exactly what you'll need to turn off. This is dictated by your site and what you want to track.
On the plus side, I can tell you where to go in your Google Analytics account to turn off some default tracking events. So here goes:
In your Google Analytics account, right in the bottom left hand corner there's a cog icon:
Click the cog icon, then expand the "Data Collection and Modification" section, and then click on "Data Streams":
Then click on the arrow on the same line as your site's data stream:
The click on the cog icon in the "Events" section:
And you're then presented with some on/off options. If you're able to, disbable as many of these as you can, then click save:
You might need to repeat this process for any custom events that you've set up, should there be any that you can remove.
After saving your changes, you'd then need to have hte CAOS plugin create a new local copy of the tracking JavaScript which will now be smaller due to you disabling tracking events in your Google Analytics account.
You'd do this in your WordPress, by clicking on:
Plugins > Installed Plugins > Settings (in the CAOS section) and then clicking on "Regenerate Alias(es)" at the top of the page:
CAOS will the generate a smaller local file with the traching JavaScript contained within.
You might have to experiment with things a bit to check that you're tracking what you need to and not tracking what you don't need to by disabling and enabling tracking options in your Google Analytics account.
Optimising the local CAOS generated tracking script.
After carrying out the above, you'll have reduced the size of the tracking script, and localised it (to minimise DNS), but there are some further steps you can take to both reduce the size of the tracking script even further, and to make your site load it in a more efficeint manner. You'd do this by calling the tracking script using the defer directive, and by minifying the tracking script.
Calling the tracking script using defer.
Although the CAOS plugin is very helpful in what it does, the free version of this plugin only allows you to call the Google Analytics script with the async attribute.
The async attribute is used to tell browsers that the script should be loaded in the background while the HTML parsing continues, and then to execute the script once it's loaded. So the script is downloaded at the same time that the HTML parsing is taking place.
This can still be flagged as a problem in page speed insights because according to Google's Lighthouse documentation covering unused Javascript:
"Even if the JavaScript is asynchronous (not render-blocking), the code competes for bandwidth with other resources while it's downloading, which has significant performance implications. Sending unused code over the network is also wasteful for mobile users who don't have unlimited data plans."
This can be addressed by using the defer attribute instead of async. This tells the browser to delay the downloading the downloading of the script, until the HTML parsing is complete. It's the equivalent of saying "download this script after the page has been generated".
The problem is that the CAOS plugin doesn't provider you with a option to defer the script, but this can be done externally to the CAOS plugin. The information you'll need to do this you can obtain from the CAOS plugin itself, and you'd bring this information in to effect using a plugin that allows you to insert code in to the and at the bottom of the of your site's pages.
The plugin I'm going to use to do this is the WPcode plugin. You'd install and activate this plugin just like you would any other. Go ahead and install this now if you're following this guide as a walkthrough.
Then, to obtain the information you'll need hover over Settings (in the menu on the left hand side) and then click on "Optimise Google Analytics":
You'll then see the CAOS settings. In these settings In the "Tracking Code Position" select "add manually", then click "Save changes":
Stay on the screen that's displayed above for the moment, because we're going to add what's in the "Tracking-code" section of the above to manually add the script to your site.
The first part we'll need is the part that calls the script using a URL, so copy this part:
And then paste it in to a text editor:
Then simply change the word async to defer:
Then select all the text, right click on it, then click on "copy":
The go to the "headers and footer" part of Code Snippets by hoverring over "Code Snippets" in the menu on the left hand side, then clicking on "Header and Footer".
And paste to code that you copied from the text editorin in to the "header" section. Then save your changes:
You're now calling the script using the defer attribute on your site's pages.
There is a bit more that we need to do, though. If you go back to
Settings > Optimise Google Analytics
In the "Tracking-code" section, you'll see a bit of code that we haven't taken in to account (the highlighted section in the screen shot below:
What this script does is (very generally speaking) make use of the script that we deferred and added to , and captures events to send back to Google so you can see the events in your Google analytics dashboard, so we need to add this as well.
You can simply take a copy of this script:
And then, to add the script to your site, hover over "Code Snippets" in the menu on the left hand side, then click on "Header and Footer":
and then paste the script in to the "footer" section, and then save your changes:
This is the most sensible thing to do if you're using more of Google Analytics features and have (or want to be able to use) custom tacking events. That said, there is still a performance decrease in page speed insights. Not much, but still a decrease.
On the other hand, if you only need basic Google Analytics type tracking (number of visitors, visitor locations, basic demographic details) instead of using the script you obtained from CAOS, you can use this in the footer section of code snippets:
<script id="caos-gtag-js-after">window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
ga('create', 'YOUR-TRACKING-ID-HERE', 'auto');
ga('send', 'pageview');
</script>
Like this (obviously you'll need to replace YOUR-TRACKING-ID-HERE with your actaul tracking ID):
This smaller piece of code has less of an overhead for the browser, simply because you're asking less of it. Due to this there's less of a performance decrease reported by page speed insights. It's fine to use this if you use a basic feeatures in Google Analytics. If you're using more features in Google Analytics you're likely to need the larger piece of code.
Preconnect to www.google-analytics.com
Preconnect can be used to tell the browser to connect to an external resource sooner than it normally would. You can find an entire post covering how preconnnect, preload and prefetch can be used here.
The google analytics script is going to connect to www.google-analytics.com to collect the stats you see in your google analytics account. So it's going to have to tell the browser to connect to www.google-analytics.com at some point.
You can instruct the browser to connect to www.google-analytics.com in advance of when it normally would (to reduce the time it takes to collect and report stats) by adding this to your site's <head>:
<link rel='preconnect' href='//www.google-analytics.com' />
Again, you'd use the Header and Footer section of the Code Snippets plugin to do this. In the Header section add the code above, then click "Save changes":
Minifying the tracking script.
Minifying strips all the parts of a piece of code that aren't required for it to run, such as comments and whitespace. The effect of this is that it makes the size of the file containing the code smaller. This results in less data being transferred when someone visits a page on your site.
Some caching plugins can be used to do this, and it can also be carried out manually. I'll cover how to manually do this, just in case your caching plugin doesn't provide this facility.
To manually minify, you'd locate the localised tracking script in your hosting file manager:
- Open the file manager
- Browse to document_root/wp-content/uploads/caos
- Right click on the .js file
- Click on edit
Then select all the code on the page, right click and click on "copy":
The browse to an online JavaScript minifiying service, such as https://www.toptal.com/developers/javascript-minifier . Right click on the area where you'd enter the code to be minfied, then select paste:
Then click the minify button:
Then copy the minified code:
Then go back to the original file in your hosting, select all the code, then right click, click paste and save:
I've (so far!) found that what I've covered above is the "cheapest" (most minimal overhead) way of using basic Google Analytics type tracking on a website, without having to learn JavaScript.
The benefits of reducing unused JavaScript when using Google Analytics.
The total effect of the above is:
- Reduced data transfer due to reducing the size of the tracking script and minifying the tracking script.
- Calling the tracking script in manner that doesn't result in it being render blocking.
From a practical point of view, this translates to faster page load times, so a better experience for your website visitors and an improved performance metric in Page Speed Insights, which may positively affect your website's pages ranking positions.
In Conclusion.
- It can be disheartening to have Page Speed Insights flag the Google Analytics tracking code as a problem on your site.
- The CAOS plugin can be used (if you're using WordPress) to host the Google Analytics tracking script locally.
- The size of the Google Analytics tracking script can be reduced by tracking less events as configured in your Google Analytics account.
- Aliases need to be regenerated in the CAOS plugin's settings after modifying events in your Google Analytics account.
- You can call the tracking script in a more efficient manner by using the defer attribute and the code snippets plugin to add the URL of the tracking script and the additional JavaScript.
- Minifying the local tracking script will reduce it's size to result in less data transfer on page load.