Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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