Putting Piwik.js in a CDN


My site is at ‘www.domain.com’ which is a dedicated server.
I host all images, css, and js on ‘cdn.domain.com’ which is amazon cloudfront
I’ve got piwik at ‘stats.domain.com’ on the same dedi server.

Is there a way to put piwik.js so it loads off the CDN ?

I assume this will require modification of the stats code …but I’m not sure what to edit.


Simply change the path to piwik.js to the CDN and it will work fine! :slight_smile:

Can someone explain the proper way to do this? I’ve placed piwik.js on a CDN & updated the script on my website to point to it. I’m no longer tracking visits.

<!-- Piwik --> 
<script type="text/javascript">
var pkBaseURL = (("https:" == document.location.protocol) ? "https://xx.rackcdn.com/" : "http://xx.rackcdn.com/");
document.write(unescape("%3Cscript src='" + pkBaseURL + "piwik.js' type='text/javascript'%3E%3C/script%3E"));
</script><script type="text/javascript">
try {
var piwikTracker = Piwik.getTracker(pkBaseURL + "piwik.php", 1);
} catch( err ) {}
</script><noscript><p><img src="http://my-piwik-server.com/piwik.php?idsite=4" style="border:0" alt="" /></p></noscript>
<!-- End Piwik Tracking Code -->

I’ve also tried moving the php file & updating that URL as well, but that didn’t help.

It took me a while, but I got it :o

<!-- Piwik --> <script type="text/javascript">
var _paq = _paq || [];
(function(){ var u=(("https:" == document.location.protocol) ? "https://piwik.domain.com" : "http://piwik.domain.com/");
_paq.push(['setSiteId', 1]);
_paq.push(['setTrackerUrl', u+'piwik.php']);
var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; g.type='text/javascript'; g.defer=true; g.async=true; g.src='http://cdn.domain.com/piwik.js';
s.parentNode.insertBefore(g,s); })();
<!-- End Piwik Code -->

Wow, excellent work. Gave the correct answer, inside of 5 mins, and beat me to my next question (async). That’s a hat trick. I just tried this and it works. Thank you!

Took me a while to find the async code too.
Why isn’t it default anyway ?

Sorry it’s annoying to have to change the code manually, we will fix it soon: Improve Javascript Tracking Code admin screen: asynchronous code, other options · Issue #1845 · matomo-org/matomo · GitHub


Is it up yet?