Correctly executing a third party on page view, interactive or onload + code

Correctly executing a third party on page view, interactive or onload + code

Whatever you do as a third party, there's an interesting nuance that we ran into with a Matomo implementation. The issue: the website was too quick.

Because the website was so quick - and it still is ;) -, the interactive event already happened before Matomo was loaded. But Matomo was actually patiently waiting for that the readystatechange event to then load itself on readyStateinteractive.

End-result:

  • Matomo did not had the chance to hook itself into the website as that event already happened before Matomo was loaded
  • Less visitors were tracked 😅
  • we spotted this as RUMvision was tracking way more pageviews

So, the code below is the way to go:

  • the code doesn't just try to hook itself into the website using a specific event
  • but also checks if the event might have happened somewhere before already
  • and is then allowed to load itself right away
const eventTrigger = 'interactive'; // could also be "onload" or "direct"
if ( eventTrigger == 'interactive' && document.readyState == 'loading') {
document.addEventListener('readystatechange', function(){
if ( document.readyState == 'interactive' ) {
initWidget();
}
});
} else if ( eventTrigger != 'onload' || document.readyState == 'complete') {
initWidget();
} else {
window.addEventListener('load', initWidget);
}

What it does:

  • if you want initWidget to execute on interactive, but the state isn't there yet, we want to hook an event listener into readystatechange.
  • If your desired event or trigger isn't equal to onload or the loading state of the document was completed already, we're ok to directly execute initWidget. Because of the OR clause in the if-statement, this also covers a situation where you want initWidget to be executed directly.
  • If you actually meant to execute initWidget on onload, but the document isn't just there yet, we can hook into the load-event using an event listener.

For third parties

If you're a third party, you might want to give users the option to determine when your third party should be executed. The above code actually is what RUMvision is using to keep site-owners in control.

But when doing so, the above is important to know as each website might have a different loading speed, and events will be executed at different moments. Especially when taking into account that visitors and their device and internet speed will impact metrics and events as well.

For merchants, agencies or developers

The code above could be adjusted to your needs. For example to bulk-load third parties per preferred trigger-type.

However, if you're using a (Adobe or Google) tag manager already, you might want to use that to add third parties to specific events. Those third parties should then do the heavy lifting for you (be sure to test this though, to prevent the issue we have with Matomo).