I\'m on a quest to reach 100/100 on PageSpeed and i\'m almost there. I\'m trying to find a good solution to cache Google Analytics.
Here is the message I get:
Here is a really simple solution using JS, for basic GA tracking, which will also work for edge caches/proxies (this was converted from a comment):
if(navigator.userAgent.indexOf("Speed Insights") == -1) {
(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.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXXXXXX-X', 'auto');
ga('send', 'pageview');
}
Note: This is the default GA script. You may have other ga()
calls, and if so, you would need to always check the user agent before calling ga()
, otherwise it may error out.