Reputation: 356
When installing Google Analytics the latest version of their code (for Universal Analytics) is as follows:
(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', '//www.google-analytics.com/analytics.js', 'ga');
ga('create', 'UA-XXXXXXX-X', 'auto');
ga('send', 'pageview');
The first part of the code creates a <script>
tag to load analytics.js
, then the second part uses the ga()
function to activate the script.
My question is - if it takes some time to load analytics.js
, how does the ga()
function know to wait before being executed? Why doesn't ga()
try to run before the script has loaded?
I'd like to use a similar mechanism and hoped understanding Google's code better will help.
Upvotes: 1
Views: 1120
Reputation: 2452
It was more clear in the the ga.js
codebase than it is here, but it's the exact same principle.
For analytics.js
it's pretty much the same thing but wrapped in a function (which can be renamed). To answer your question, the link you sent pretty much sums it up but for clarity: since the code block includes the initialization for the temporary solution (push the commands to the array but not actually execute the commands), ga()
exists and therefore will run without error.
Upvotes: 3