Speculation Rules API (rel=prerender)

With a prerend speculation rules or a <link rel="prerender" (relation web pages might be loaded without a visitor actually viewing the page. This can be prevented by wrapping the trackPageView in a prerenderingchange listener:

if (document.prerendering) {
    document.addEventListener('prerenderingchange', () => {
        _paq.push(['trackPageView']);
    }, {
        once: true,
    });
} else {
    _paq.push(['trackPageView']);
}

we have to do that in tracking code if we want to use speculations rules API?

<!-- Matomo -->
<script type="text/javascript">
  var _paq = window._paq = window._paq || [];
  if (document.prerendering) {
    document.addEventListener('prerenderingchange', () => {
        _paq.push(['trackPageView']);
    }, {
        once: true,
    });
} else {
    _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 -->

Yes, it replaces the existing _paq.push([‘trackPageView’]);

In mode=prerender, (and eagernes not set to moderate) all interactive JavaScript must be paused. Until the page is actually visited. The code in the original post is one solution.

I couldn’t find a native solution within Matomo.

You could also wrap the whole tracking code in a function. See below. That should work fine since the tracking does not affect the DOM and the tracking code is already loaded on the current page, so fetched from cache on the next one.

I have no idea, how this affects the performance reports like the dom-render time.



function initMatomo() {
  /* your matomo code goes here */

}

if (document.prerendering) {
    document.addEventListener('prerenderingchange',initMatomo, {
        once: true,
    });
} else {
    initMatomo();
}

Prefetching/prerendering has quite a few side effects. Think about links like ‘logout’ and ‘add to shopping chart’. But that is beyond Matomo.

1 Like