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.jsexpects a global variablewindow._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>