Deferred js loading with Matomo Code

Hi there!
I’m kind of confused.
I use both Inspectlet and Matomo on my site.
Code for both of these are in a javascript file that also contains jquery and more so it’s quite heavy. I defer load this js-file with the Google recomended way like so:

<script type="text/javascript">
			function downloadJSAtOnload() {
			var element = document.createElement("script");
			element.src = "<?php bloginfo('template_directory'); ?>/defer.js";
			document.body.appendChild(element);
			}
			if (window.addEventListener)
			window.addEventListener("load", downloadJSAtOnload, false);
			else if (window.attachEvent)
			window.attachEvent("onload", downloadJSAtOnload);
			else window.onload = downloadJSAtOnload;
</script>

My problem is that my statisitcs doesn’t seem to be correct in Matomo.
Some visits are reported as 1 sec in Matomo but in Inspectlet they are complete sessions with visits to subpages and all. I do see this because they are connected to a “campaign” variable in a specific mail.

Any idea as to why this is happening?
Is it not a good solution to use the Matomo code in a defered loaded file?
As I mentioned it’s quite heavy - 150kB or so so it take some time to load…

Best, Niklas

Hi,

I don’t think you need such an complicated way to load a js file deferred as every browser supports this out of the box by specifying

<script defer async src='https://example.com/test.js'></script>

If you just use the default tracking code, Matomo will be loaded deferred and therefore won’t slow the pageload down.