简体   繁体   中英

Google Analytics javascript

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM