Skip to content

Instantly share code, notes, and snippets.

@nateberkopec
Forked from tomfuertes/0.result.md
Last active January 18, 2024 11:20
Show Gist options
  • Save nateberkopec/a43f3e29d9583df33406 to your computer and use it in GitHub Desktop.
Save nateberkopec/a43f3e29d9583df33406 to your computer and use it in GitHub Desktop.
De-'Async Inject'ing Universal Analytics

De-'Async Inject' Universal Analytics

This gist applies the theory from Ilya Grigorik's Script-injected "async scripts" considered harmful on the default Universal Analytics snippet. TLDR place this above the CSS in the <head> of your document

<!-- Google Analytics Part 1: Creates window.ga, sets account, and queues pageview-->
<script>
  !function(n,t){n.GoogleAnalyticsObject=t,n[t]=n[t]||function(){(n[t].q=n[t].q||[]).push(arguments)},n[t].l=1*new Date}(window,"ga");
  ga('create', 'UA-XXXX-Y', 'auto'); // REPLACE UA-XXXX-Y w/ YOUR ACCOUNT
  ga('send', 'pageview');
</script>
<!-- End Google Analytics Part 2 -->

And then place this below your CSS in the <head>:

<!-- Google Analytics Part 2: load analytics.js-->
<script async src='//www.google-analytics.com/analytics.js'></script>
<!-- End Google Analytics Part 2 -->
<!-- Google Analytics -->
<script>
(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');
ga('create', 'UA-XXXX-Y', 'auto');
ga('send', 'pageview');
</script>
<!-- End Google Analytics -->
<!-- Google Analytics -->
<script>
(function(window, document, strScript, url, variableName, scriptElement, firstScript) {
window['GoogleAnalyticsObject'] = variableName;
window[variableName] = window[variableName] || function() {
(window[variableName].q = window[variableName].q || []).push(arguments);
};
window[variableName].l = 1 * new Date();
scriptElement = document.createElement(strScript),
firstScript = document.getElementsByTagName(strScript)[0];
scriptElement.async = 1;
scriptElement.src = url;
firstScript.parentNode.insertBefore(scriptElement, firstScript)
})(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
ga('create', 'UA-XXXX-Y');
ga('send', 'pageview');
</script>
<!-- End Google Analytics -->
<!-- Google Analytics -->
<script>
(function(window, variableName) {
window.GoogleAnalyticsObject = variableName;
window[variableName] = window[variableName] || function() {
(window[variableName].q = window[variableName].q || []).push(arguments);
};
window[variableName].l = 1 * new Date();
})(window, 'ga');
ga('create', 'UA-XXXX-Y');
ga('send', 'pageview');
</script>
<script async src='//www.google-analytics.com/analytics.js'></script>
<!-- End Google Analytics -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment