13

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,696
  • 18
  • 29
xela84
  • 214
  • 2
  • 9

2 Answers2

9

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
  • 10,737
  • 3
  • 56
  • 68
  • 1
    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
0

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
  • 10,737
  • 3
  • 56
  • 68