Skip to content

Commit

Permalink
Avoid serving the GA script to PageSpeed Insights
Browse files Browse the repository at this point in the history
Google PageSpeed Insights tool often shows a "Leverage Browser Caching"
penalization when one is using Google Analytics with the recommended
installation method. This sounds very counter-intuitive given that both
tools come from Google themselves.

This works around that issue by conditionally loading Google Analytics
only if the page is not being crawled by Google PageSpeed Insights bot.

Google is cheating me, so I'm cheating Google back... ¯\_(ツ)_/¯
  • Loading branch information
rfgamaral committed Nov 3, 2017
1 parent fd3606d commit a161379
Showing 1 changed file with 21 additions and 6 deletions.
27 changes: 21 additions & 6 deletions src/ssi/gtag.html
Original file line number Diff line number Diff line change
@@ -1,9 +1,24 @@
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-108806299-1"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() { dataLayer.push(arguments); }
gtag('js', new Date());
if (navigator.userAgent.indexOf('Google Page Speed Insights') === -1) {
var TRACKING_ID = 'UA-108806299-1';

gtag('config', 'UA-108806299-1');
var gtagElement = document.createElement('script');

gtagElement.async = true;
gtagElement.src = 'https://www.googletagmanager.com/gtag/js?id=' + TRACKING_ID;

var scriptElements = document.getElementsByTagName('script');
var lastScriptElement = scriptElements[scriptElements.length - 1];

lastScriptElement.parentNode.insertBefore(gtagElement, lastScriptElement.nextSibling);

window.dataLayer = window.dataLayer || [];

function gtag() {
dataLayer.push(arguments);
}

gtag('js', new Date());
gtag('config', TRACKING_ID);
}
</script>

0 comments on commit a161379

Please sign in to comment.