I am trying to modify a js snippet that creates a js tag, it currently uses document.write which breaks the page removing all the existing DOM elements. I wanted to use something like google analytics does, my current code looks something like this:
var scr = document.createElement('script');
scr.type = 'text/javascript';
scr.async = true;
scr.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'cdn.myurl.com/myscript.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(scr, s);
stuff.somefunc({
userID: '2312312'
});
My problem is that stuff is obviously undefined, I want to avoid using some onload methods since I tried it in the past and had problems in some browsers. I tried to figure out how google analytics do it but my js skills are not that great. Here's the analytics sample:
(function (i, s, o, g, r, a, m) {
window['GoogleAnalyticsObject'] = 'ga';
window['ga'] = window['ga'] || function () {
(window['ga'].q = window['ga'].q || []).push(arguments)
}, window['ga'].l = 1 * new Date();
a = document.createElement('script'),
m = document.getElementsByTagName('script')[0];
a.async = 1;
a.src = '//www.google-analytics.com/analytics.js';
m.parentNode.insertBefore(a, m)
})(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
ga('create', 'UA-xxxxxxxx-x', 'xxxxxx.com');
ga('send', 'pageview');
How are they able to run ga()? As far as I can tell they are creating a global func with window['ga'] and pushing the arguments into an array to window['ga'].q, but what then? Is that window['ga'] function called inside analytics.js file? How?