Reputation: 312
I try to update my Google Analytics implementation from analytics.js to the new gtag.js.
In the old implementation I am using the ready callback function.
ga(function() {
console.log('Google analytics is ready');
});
How can I implement a ready callback in the new gtag.js? I can't find any information in Google's documentation.
Upvotes: 20
Views: 9000
Reputation: 191
You should be mindfull that under many scenarios the event_callback would not be called:
If you nedd a strong guarantee of the event being fired (ie you wat to go to the app page after logging the "login" event) you'd need to redefine the gtag
function:
function gtag() {
if (arguments[2] instanceof Object && arguments[2]["event_callback"] instanceof Function) { // We have a callback to call
var cb = arguments[2]["event_callback"]
var tid = window.setTimeout(cb, 200) // call soon just in case the event fails to deliver
arguments[2]["event_callback"] = function() {
window.clearTimeout(tid) // no need to call on our own
cb() // go
}
}
window.dataLayer.push(arguments);
}
Upvotes: 0
Reputation: 14571
The command event
supports the parameter event_callback
, a function called when processing has completed. So, compared to the old analytics.js
, you need to send an event to trigger the callback.
For example, you can use the page_view
event; however, to avoid duplicates, you must disable the automatic page_view
event by setting send_page_view
to false
.
gtag('config', GA_TRACKING_ID, {
'send_page_view': false
});
gtag('event', 'page_view', {
'event_callback': function() {
console.log('Google Analytics is ready');
}
});
Upvotes: 15
Reputation: 14571
A simpler (but probably less reliable) solution is to use the onload
attribute of the <script>
tag:
<script async src="https://www.googletagmanager.com/gtag/js?id=GA_TRACKING_ID"
onload="console.log('Google analytics is ready');">
</script>
Upvotes: 2