If you want to look at a more practical case, we can talk about Google Ads conversion tracking and gtag in general, together with cookie consent banner. It is trivial on a normal website, but becomes much more complex with Turbo. The hard part is that you cannot adapt, change or read the code of the gtag.
<div data-controller="consent" data-consent-target="banner" data-turbo-temporary>
<p>
Please select whether you consent to our use of cookies and related technologies.
</p>
<div>
<button type="button" data-action="click->consent#decline">
Decline
</button>
<button type="button" data-action="click->consent#accept">
Accept
</button>
</div>
</div>
This seems to work, but I see that it includes the gtag script in the head more than 1 time (you can see that if you inspect the document body).
Are there any better solutions?
Do you have any examples of implementation of gtag and Turbo?
I don’t have any examples sorry. I will test yours later and look for a turbo way, but meanwhile, for the tag script to not duplicate, it should be enough if you add a unique id to the script tag and you check if that ID exists before adding the script.
if (document.getElementById("gtag")) return;
var script = document.createElement('script')
script.src = 'https://www.googletagmanager.com/gtag/js?id=AW-12345'
script.async = true
script.id = "gtag"
...
I already tried to check for presence of the script and not include it, however this creates other issues with tracking: if I remember properly, it didn’t track all the page views if I don’t include the script again on every page load.
I get it, I had a similar issue, but as I had control over the javascript code, I just modified it to listen for turbo events.
Anyway, when navigating with turbo, your page works similar to an SPA, but turbo properly uses the History API, so maybe it is worth to try the History Change trigger type in Gtag.