2

Here is a Google Analytics' code

var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-20366831-2']);
_gaq.push(['_trackPageview']);
(function () {
 var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
 ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
 var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

How my client side calls Google anonymous function?

fernandopasik
10.7k7 gold badges52 silver badges56 bronze badges
asked Dec 12, 2011 at 22:27

2 Answers 2

5

It's called because the anonymous function ends with ()

 var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})(); // <--- The () calls the anonymous code

As you'll see, this code basically injects a script tag into the DOM, which gets run by the browser.

answered Dec 12, 2011 at 22:29
Sign up to request clarification or add additional context in comments.

Comments

0

That snippet already call itself.

(function () {
 var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
 ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
 var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})(); 

what it actually does is including the ga.js on your page, which is similar to this:

<script src="//google-analytics.com/ga.js" />

The rest is up to you to add event to the _gaq (google analytic queue). Then the event will automatically be processed.

answered Jan 27, 2015 at 19:21

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.