javascriptgoogle-analyticsgtag.jsanalytics.js

Difference between Google Analytics script snippets analytics.js and gtag.js


Setting up Google Analytics on one of the websites I have discovered that tracking code snippet provided for embedding in Analytics settings has different syntax and linked JS script than the one, that I have used when setting up another property couple of years ago.

Snippet #1 (gtag.js) - provided by Analytics settings

<script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXX-Y"></script>
<script>
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());

    gtag('config', 'UA-XXXX-Y');
</script>

Snippet #2 (analytics.js) - used in an older website

(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-XXXX-Y', 'auto');
ga('send', 'pageview');

Documentation refers to migration from analytics.js to gtag.js in general, but without any specific deadlines. So while I am still using analytics.js on my older website the questions arise:

What are the differences (if any) of using gtag.js over analytics.js, both in collected data and in website performance?

Also, when I migrate to gtag.js on older site, are there any known hiccups in collecting data by Google Analytics? Like some data could be lost for some "propagation" period or similar...

Thanks in advance!


Solution

  • gtag.js is not a replacement library for analytics.js, it is a new method of implementation of the analytics.js library. When you look at the javascript that's loaded on a page with gtag.js, you'll see analytics.js being loaded through gtag.js. So data collection is the same.

    I would say only change it if there is a need, otherwise, leave as is. analytics.js is fine. I would say gtag.js might be more complicated in terms of implementation compared to analytics.js only because it is new and some people are more used to analytics.js and would confuse gtag() and ga() functions.