Open nickFalcone opened 1 year ago
GA4 requires much more client side JS AFAIK, so I'm not planning to add support. Legacy GA works just fine.
If you'd send a PR, I'd be happy to take a look.
Just to say I would also be interested in understanding how to do this, even if it doesn't necessarily get merged - let me know if I can assist at all.
Hi @JamesLMilner, here is what I did in my personal blog generated from the template. I see results in the ga4 dashboard so this "works" but may not be optimal given it was a self-reviewed PR over the holiday 😅. If you spot anything that could be improved, please let me know and I'll open a PR to the template.
Added a copy of gtag.js to /js
and the following to _includes/layouts/base.njk
:
<script async defer src="{{ "/js/gtag.js" | addHash }}"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'YOUR-G4-ID');
</script>
I also updated _data/googleanalytics.js
to this:
const metadata = require('./metadata.json');
module.exports = function () {
if (metadata.ga4Id) {
return metadata.ga4Id;
}
return null;
};
and replaced the googleAnalyticsId
key in _data/metadata.json
with ga4Id
. Lastly, I updated the line in .eleventy.js
to copy ga4.js
eleventyConfig.addPassthroughCopy(GA4_ID ? 'js' : 'js/*[!ga4].*');
You can of course totally do this!
It just won't have the 100% first-party support that was there for legacy GA
Tomorrow UA is officially sunset.
Support for GA4 should be added to prevent a lapse in data collection. Universal Analytics (UA) properties will stop processing data on July 1, 2023.
cached.js
contains a copy of analytics.js. I propose we add a new file,gtag.js
with the contents of https://www.googletagmanager.com/gtag/js?id=my-g-id. We would need to retrieve the user's ID from a new field inmetadata.json
. The rationale for a second file is to separate legacy analytics.js and selectively load gtag.js if the user has a GA4 ID.Other areas to update:
webvitals.js
in favor of https://web.dev/vitals-ga4/