Great question! Let's go in order:
1. Declaration and call of the main function
(function(d, w, c) { ... })(document, window, "yandex_metrika_callbacks");
Here you declare a certain function, and immediately after the declaration, you call it with the document
, window
parameters and the Yandex.Metrica string key. These parameters are used inside the function.
2. Saving Metric Constructor
w[c] = w[c] || []
w
is your browser window. In it, you can store functions or data, and they will be available globally in other scripts. In fact, here you are accessing w["yandex_metrika_callbacks"]
, and there either will already have some values (for example, from other Yandex.Metrica counters), or an empty array declared by you.
.push(function() { ... );
And then you add an element to this array (already existing or just created) - a function that tries to create a metric counter object.
w.yaCounterCOUNTER_ID = new Ya.Metrika({ .. });
Create the object again at the w
window so that it is available in any other scripts.
3. Asynchronous script load metrics
n = d.getElementsByTagName("script")[0]
Here you find the first <script>
tag on your site. The metric needs it here with this command ..
n.parentNode.insertBefore(s, n);
.. Insert a new script created by it before your existing one. Before or after - it does not matter, the main thing is to place the script on the page, and the metric does it in a guaranteed way.
It would be possible to place the script at the end of <body>
or <head>
, but recently these tags in the layout are optional. But the <script>
on your site will definitely be at least one - with the metric counter code.
s = d.createElement("script") s.type = "text/javascript"; s.async = true; s.src = "https://mc.yandex.ru/metrika/watch.js";
Here, the metric just creates that <script>
, which it then inserts into the page, and after insertion, the script will begin to load asynchronously.
f();
This is where the f function is called, which inserts the <script>
metrics into the DOM. Slightly above there is an exception, in case Opera browser is used:
d.addEventListener("DOMContentLoaded", f, false);
Which in the same way will execute function f, but after full loading of DOM'a the browser.
4. Run an asynchronously loaded script
As a result, the watch.js
script is loaded asynchronously, and in the window["yandex_metrika_callbacks"]
you have stored constructor functions for Yandex.Metrics objects.
When the watch.js
script loads, it will simply call all these functions in a row, thus initializing all the Yandex.Metrica counters that you want to see on the site.