Why some _paq.push are inside the closure in the tracking code?


(Pablo) #1

Is there a reason there are two _paq.push lines before the function closure and two inside it?
Combining all _paq.push will be easier to understand because there is no difference:

<!-- Matomo -->
<script type="text/javascript">
  (function() {
  var _paq = window._paq || [];
  _paq.push(['trackPageView']);
  _paq.push(['enableLinkTracking']);
  var u="//{$PIWIK_URL}/";
  _paq.push(['setTrackerUrl', u+'piwik.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.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s);
  })();
</script>
<!-- End Matomo Code -->

Instead of:

<!-- Matomo -->
<script type="text/javascript">
  var _paq = window._paq || [];
  _paq.push(['trackPageView']);
  _paq.push(['enableLinkTracking']);
  (function() {
    var u="//{$PIWIK_URL}/";
    _paq.push(['setTrackerUrl', u+'piwik.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.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s);
  })();
</script>
<!-- End Matomo Code -->

(Lukas Winkler) #2

Hi,

Your first example has one disadvantage: _paq is only defined inside the function and therefore you can’t use it on the rest of the website (e.g. for event tracking)


(Pablo) #3

So maybe this:

<script type="text/javascript">
  var _paq = window._paq || [];
  (function() {  
  _paq.push(['trackPageView']);
  _paq.push(['enableLinkTracking']);
  var u="//{$PIWIK_URL}/";
  _paq.push(['setTrackerUrl', u+'piwik.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.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s);
  })();
</script>

(Lukas Winkler) #4

I can’t see a disadvantage in doing it this way (which doesn’t mean there is none)

I think the main reason for the split is that _paq.push(['trackPageView']); and co. don’t have to be there. If you are writing an SPA, you still have the rest only once, but will call _paq.push(['trackPageView']); on every pageview.