You folks may or may not be aware but Google has been migrating its analytics away from what they call 'Universal Analytics' and toward the current standard, which they call 'Google Analytics 4' or 'GA4'. At the moment, googling how to do certain things most often leads to old Universal Analytics instructions with a warning that it's deprecated and a generic, unhelpful link to some hopelessly broad/introductory GA 4 topic.
I'm trying to track when users on my site click links to external sites where they can hear and/or buy my music. I see from this documentation that one can trigger an event by calling a function, gtag()
:
gtag('event', '<event_name>', {
<event_parameters>
});
It occurs to me that this event reporting function call is surely contacting the google website/api to report this event, and I am concerned that if the event is attacked to the onclick
event of an <a> tag or button, that we might encounter some kind of race condition: might the browser exit the current page, terminating all pending code execution, before the API call to google gets fired?
I note that fairly deep in the rather nebulous GA 4 documentation that there is a mention of an event_callback control parameter. I'm not even sure if this parameter applies to basic GA 4 tag I'm using:
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XXXXXXXXXX');
</script>
Or whether that event_callback function control parameter only applies when using the Google Tags approach, whose markup looks a bit more complicated.
I've so far been unable to find any onclick examples in the GA4 documentation so I'm not sure how to approach this. Ideally, I'd like to track events by remote website (i.e., bandcamp versus spotify versus itunes etc.) and also by where the click happened (e.g., home page button, testimonial popup, album information page, etc.).
Does anyone have experience with GA 4? Must we take special care to wait for a gtag operation to complete when trying to fire custom events off some onclick event that takes a user to an external website?