16

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.

Miotsu
  • 1,776
  • 18
  • 30
xela84
  • 262
  • 2
  • 10

2 Answers2

12

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'); 
  }
});
Benoit Blanchon
  • 13,364
  • 4
  • 73
  • 81
  • 2
    This is a great answer, the only thing that's missing is a reference to the documentation. Here: https://developers.google.com/gtagjs/reference/event – Patrick Mar 15 '20 at 04:56
  • Couldn't we just set like this to get the ready callback? `gtag('config', GA_TRACKING_ID, { event_callback: alert('Ready'), })` – 陳見綸 May 19 '22 at 10:44
  • Actually `'event_callback'` property doesn't seem to be in the docs – Omu Jan 07 '23 at 09:31
  • Just to note, ```gtag('config', GA_TRACKING_ID, { event_callback: alert('Ready'), })``` **doesn't** work because the ```config``` command *doesn't* call the ```event_callback``` - only the ```event``` command does that - see https://developers.google.com/tag-platform/gtagjs/reference/parameters "event_callback | function | function() { form.submit(); } | JavaScript callback function called when processing of an **event** command has completed.```... – mclayton Mar 23 '23 at 09:30
1

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>
Benoit Blanchon
  • 13,364
  • 4
  • 73
  • 81