0

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?

1 Answer 1

2

ga() is executed because of the self-invoking anonymous function (SAIF) which does exactly that - it invokes or executes itself after being defined, with the arguments as provided in the parameters at the end.

This explains the GA code in detail: http://code.stephenmorley.org/javascript/understanding-the-google-analytics-tracking-code/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.