Ad

Does Google Analytics Emit An Event When They Are Set Up?

Some of our customers want to have their Google Analytics id reported to them. It's not hard to get it.

ga.getAll()[0].get('clientId');

There is also a queued syntax, so that an operation is done when GA is set up.

But don't want to send a GA event when GA is ready. I want to ask GA a question when it is ready.

Perhaps there is some way to say to GA "When you're ready, run this function I'm passing you."

Alternatively, does GA emit a custom event when it is ready?

Currently, my customer is calling my code when window emits the load event. But even then, a fraction of the time ga isn't defined. If you wait a few seconds, it's defined. Perhaps some weird cdn system. Anyway, I need a reliable way of determine when GA is ready.


(I wasn't able to make formatting in the comments cooperate, so I changed my question to respond to Feathercrown.)

That sounds great! The only problem is that ga isn't defined yet. Here is a sample of the error message I send myself.
"type": "Page View", "data": { "error": { "message": "ga.getAll is not a function. (In 'ga.getAll()', 'ga.getAll' is undefined)", "message2": "window.GoogleAnalyticsObject = ga", "message3": "typeof ga is not Object" } },

Maybe that _gxx something symbol is already available?

Ad

Answer

Calling ga() with just a function can be used as a callback (ga(readyCallback)), as the function will only be run "when the analytics.js library is loaded and ready."

According to the documentation:

Invoking the ga() command queue function by passing it a function will schedule the passed function for execution at the next point in the queue.

Since commands are only executed after the analytics.js library is fully loaded, the most common reason to pass the command queue a function is as a callback for when the analytics.js library is loaded and ready.

Therefore, you could try:

ga(function(){var clientId = ga.getAll()[0].get('clientId');});

or something similar.

Ad
source: stackoverflow.com
Ad