Why does gatsby-plugin-google-gtag includes analytics.js and gtag.js?

337 Views Asked by At

The plugin gatsby-plugin-google-gtag adds analytics.js and gtag.js to my website. This reduces my page speed insights score. Isn't gtag.js enough ? Why do we need analytics.js ?

1

There are 1 best solutions below

0
ven42 On

It's not the Gatsby plugin that's adding analytics.js; it's Google.

I was confused by this as well when we were migrating from gatsby-plugin-google-analytics to gatsby-plugin-google-gtag, as my expectation was to see analytics.js disappear and be replaced by gtag.js in the built website. Instead, like you, I saw both analytics.js and gtag.js getting loaded and thought something was wrong.

It turns out that Google's current implementation of gtag.js is largely a wrapper around their older ("legacy", according to Google) product integration scripts like analytics.js for Google Analytics and conversion_async.js for Google Ads. Depending on which identifiers you feed to gtag.js, it will load these other scripts, whichever ones are applicable.

You can test this yourself by using your favorite ad/content blocker to stop gtag.js from loading on your website. Notice that, if you do this, the HTML to load analytics.js is nowhere to be found in the page's source code. That's because it is only injected into the code later by gtag.js at runtime, rather than by anything at Gatsby build time. If gtag.js never runs, the tag for analytics.js is never injected into the page.

Your page speed insights score has likely decreased because gtag.js is a sizeable chunk of JavaScript, and then it goes and loads the same old big analytics.js you were using before. One might ask, if I only use Google Analytics and none of the other products for which gtag.js can grab metrics, then why should I load the large gtag.js library just to chainload analytics.js instead of just loading analytics.js directly? I think there's a good argument to be made in favor of doing this, but I still favor going with gtag.js myself. Google themselves are heavily pushing adoption of gtag.js over direct calls to analytics.js, and I don't think there's any guarantee that just because gtag.js is wrapping analytics.js today it will still be doing so tomorrow. Basic laws of API usage apply: as a developer, I should be writing to the interface and not counting on particularities of the implementation, since those can be changed by the API provider at will as long as the interface remains stable.