I'm trying to figure out which is the best way to use google analytics for tracking pageviews and events in a third party javascript widget (not iframe). I know that I can use multiple named trackers, but my problem is, how can I be sure that I only load analytics.js if it's not already loaded on the host page?
I have been looking at solutions like
if( window.ga && ga.create ) ...
and checking window.GoogleAnalyticsObject and return the analytics object.
But there seems to be problem with both of them. You can't use window.ga because you don't know if the object has a custom name. And from what I read in comments to similar questions the GoogleAnalyticsObject is not guaranteed to be there.
So my question is, is there a 100% safe way to know if the analytics library has already been loaded? Or is using google analytics in third party javascript always a bit insecure? ( I will only use tracking if the owner of the page gives approval )