Setting matomo tracking code in an external JS file


(Tuck Q) #1

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.


(Lukas Winkler) #2

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).


(Tuck Q) #3

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”.


(Lukas Winkler) #4

Hi,

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


(Tuck Q) #5

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?


(Lukas Winkler) #6

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.


(Tuck Q) #7

Hello Lukas,

Thank you for your quick reply.

I fixed the code and it started working fine!

Thank you very much for your help!