Setting matomo tracking code in an external JS file

I use single matomo tracking code for multiple sites as follows.

root/
├ siteA/index.html (tracking code embedded here)
├ siteB/index.html (tracking code embedded here)
├ siteC/index.html (tracking code embedded here)

To avoid redundancy to modify the embedded code, I would like to set the tracking code in an external JS file, and include it into all the sites I manage.

Bellow is how I set the external tracking code, but it is not working.
It just doesn’t measure anything and it seems there seems a problem with tracking.

root/
├ TrackingCode.js (tracking code embedded here)
├ siteA/index.html (TrackingCode.js is included here)
├ siteB/index.html (TrackingCode.js is included here)
├ siteC/index.html (TrackingCode.js is included here)

Is it possible to set matomo tracking code like above?

I appreciate, if anyone can help me with this issue.

Hi,

What you are doing should be working. So you’ll need to check your browsers developer tools to find out why it isn’t (error in the console and piwik.{js|php} in the network tab)

But you have to keep in mind, that the tracking code needs to be loaded before you can access any _paq() functions (e.g. to track events). And therefore the extra request will probably slow down the page load as the execution halts until the file has finished loading (this should be less of an issue with HTTP 2.0).

Hello Lukas,

Thank you for your reply.

I checked chrome developer console and I found out an error “Uncaught SyntaxError: Unexpected token”.

Do you have any ideas how I can fix this?

Regarding piwik.{js|php} in the network tab, I could not find the file. Only file I found was “content.css”.

Hi,

This means that the JavaScript on this page is somewhere invalid. The error message should show you where exactly.

Hello Lukas,

Here is the exact error message I get.

“include_matomo.js:1 Uncaught SyntaxError: Unexpected token <”

Yet, I don’t see any problem with the first line of the code.

Bellow is the URL I am working on.

http://キャリ婚感想.xyz/

If possible, could you take a look?

Hi,

Very quick fix: http://1000miles.mixh.jp/include_matomo.js is a javascript file, but you have included the HTML <script> part.

So remove the <script type="text/javascript"> and </script> and it should be working fine.

Hello Lukas,

Thank you for your quick reply.

I fixed the code and it started working fine!

Thank you very much for your help!