Reputation: 19207
I need to retrieve the Google Analytics Tracking ID via JavaScript for use in another script. Something like:
var ga_id = (typeof ga !== 'undefined') ? ga.getAll()[0].get('trackingId') : 'Unable to retrieve GA id'
My Analytics is loaded using Tag manager, so even though I'm running my own JavaScript quite late in the page, its not detecting the presence of the ga
object. ( I can access it without a problem via the developer tools console.)
How can I ensure that ga
has loaded before trying to access its properties?
Upvotes: 1
Views: 161
Reputation: 8081
It's there on window loaded and you can see it in the GTM preview like so:
I have this CJS in that var (used your code):
Although this is ample in my case, yours may differ, so what you can do is the following:
This is not very elegant, but it'll work. Again, for normal implementations, Window Loaded should be ample.
Upvotes: 1