Async Javascript Piwik tracking code

By default Piwik uses a very long piece of Javascript code with a lot of variables. But a lot of this code can be removed to speed things up. I came up with this code, based on the Google Analytics tracking code that works perfectly fine for the Piwik Javascript Tracking code:

<script type="text/javascript">
var _paq = [
['setSiteId', <Site ID in Piwik>],
['setDoNotTrack', 1],
['setTrackerUrl', 'http://<webhost>/piwik.php'],
['trackPageView'],
['enableLinkTracking']
];
(function()
{
var g = document.createElement('script'); g.type = 'text/javascript'; g.async = true; g.src = '//<address on which piwik.js is located>/piwik.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(g,s);
}
)
();
</script>

The code has been de-minified and a few things are important:

  • setSiteId – You have to set the SiteID correctly. You can find this ID in Piwik > Settings > Websites
  • setTrackerUrl – On which webhost is Piwik located? This URL has to refer towards that address or otherwise statistics cannot be collected!
  • setDoNotTrack – If people have configured their browser to send the DoNotTrack header, respect this and do not track those people in the statistics.
  • g.src – You can use another webhost to serve piwik.js for speed optimization. Preferably from a cookie-free domain.

The full minified tracking code:

<script type="text/javascript">
var _paq = [['setSiteId', X],['setDoNotTrack', 1],['setTrackerUrl', 'http://stat.domain.com/piwik.php'],['trackPageView'],['enableLinkTracking']];(function(){var g = document.createElement('script'); g.type = 'text/javascript'; g.async = true; g.src = '//cdn.domain.com/piwik.js';var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(g,s); })();
</script>