Why is the Matomo tracking code the way it is

Viewed 270

The default code to include Matomo analysis in a website looks like this:

<!-- Matomo -->
<script type="text/javascript">
  var _paq = window._paq = window._paq || [];
  _paq.push(['trackPageView']);
  _paq.push(['enableLinkTracking']);
  (function() {
    var u="//{$MATOMO_URL}/";
    _paq.push(['setTrackerUrl', u+'matomo.php']);
    _paq.push(['setSiteId', {$IDSITE}]);
    var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
    g.type='text/javascript'; g.async=true; g.src=u+'matomo.js'; s.parentNode.insertBefore(g,s);
  })();
</script>
<!-- End Matomo Code -->

I wonder why this is so complicated:

  • matomo.js expects a global variable window._paq. Why not directly initialize it:

    window._paq = [['trackPageView'], ['enableLinkTracking'], ...];

  • What is the immediately invoked function expression doing? Just to hide 'u', 'd' and so on from the global scope?

  • A script is inserted by DOM manipulation. Wouldn't it be simpler to just place a <script src="matomo.js"></script> tag after this block?

Edit with the information I was looking for, because I can't answer myself anymore:

As René Roth answered, the code does nothing except the obvious - it sets or extends _paq, and includes the other script. It is fully equivalent to this, which doesn't look obfuscated:

<script type="text/javascript">
window._paq = [
    ['trackPageView'],
    ['enableLinkTracking'],
    ['setTrackerUrl', '//matomo.example.com/matomo.php'],
    ['setSiteId', '2'],
]
</script>
<script src="//matomo.example.com/matomo.js" type="text/javascript" async="true"></script>
1 Answers

matomo.js expects a global variable window._paq. Why not directly initialize it:

window._paq = [['trackPageView'], ['enableLinkTracking'], ...];

There might be instances where the _paq variable is already defined and includes some additional options you might want or need. In this case, this way of initializing prevents overriding the pre-defined options.

What is the immediately invoked function expression doing? Just to hide 'u', 'd' and so on from the global scope?

It is best practice to not pollute the global namespace with variables, you might already have a variable named u or d in the global scope.

A script is inserted by DOM manipulation. Wouldn't it be simpler to just place a tag after this block?

You could do this, but then you'd need to make sure _paq is defined before the script gets called. This way, all relevant information is in one place and the options are definitely set before the main matomo script is run.

Related