Reputation: 2748
I have this code decorating urls with Analytics' cookie in my webpage.
var tracker = window[window.GoogleAnalyticsObject].getAll()[0];
new window.gaplugins.Linker(tracker).decorate("http://www.toto.com");
This occurs an error :
window[window.GoogleAnalyticsObject].getAll is not a function
window.gaplugins is undefined
Like Google Analytics load its plugin asynchrously, i imagine getAll()
and gaplugins.linker
functions are not declared yet.
I can't wait the DOM ready, so i would like to force synchrously GA plugin loading.
Thanks for your help
Upvotes: 1
Views: 846
Reputation: 2748
Using the documentation here (cf Eduardo comments), we could Post a message to the child iframe :
<iframe id="destination-frame" src="https://destination.com"></iframe>
<script>
ga('create', 'UA-XXXXX-Y', 'auto');
ga(function(tracker) {
// Gets the client ID of the default tracker.
var clientId = tracker.get('clientId');
// Gets a reference to the window object of the destionation iframe.
var frameWindow = document.getElementById('destination-frame').contentWindow;
// Sends the client ID to the window inside the destination frame.
frameWindow.postMessage(clientId, 'https://destination.com');
});
</script>
And in the iframe side :
window.addEventListener('message', function(event) {
// Ignores messages from untrusted domains.
if (event.origin != 'https://destination.com') return;
ga('create', 'UA-XXXXX-Y', 'auto', {
clientId: event.data
});
});
Upvotes: 0
Reputation: 22834
Instead of forcing it execute syncronously the best option is to use a callback function to execute your code.
Like this:
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXXX-1', 'auto');
ga('send', 'pageview');
ga(function(){
// Code in here will only run after ga is loaded.
window.tracker = window[window.GoogleAnalyticsObject].getAll()[0];
new window.gaplugins.Linker(tracker).decorate("http://www.toto.com");
})
Upvotes: 1