To integrate Google Analytics into an Ionic application, you need to handle the fact that Cordova may not be loaded immediately. The solution is to create a polling function that waits for the library to become available.

Initialization in app.js

function _waitForAnalytics() {
  if (typeof analytics !== 'undefined') {
    $cordovaGoogleAnalytics.startTrackerWithId('UA-XXXXXXXX-1');
  } else {
    setTimeout(function() {
      _waitForAnalytics();
    }, 250);
  }
}
_waitForAnalytics();

Tracking page views

In each controller, use the same polling pattern:

function _waitForAnalytics() {
  if (typeof analytics !== 'undefined') {
    $cordovaGoogleAnalytics.trackView('Home');
  } else {
    setTimeout(function() {
      _waitForAnalytics();
    }, 250);
  }
}
_waitForAnalytics();

The 250ms interval ensures the check isn’t too aggressive while still initializing tracking quickly once Cordova is ready.