Piwik (analytics software), works by including a small script just before the </body>
:
<script type="text/javascript">
var _paq = _paq || [];
_paq.push(['trackPageView']);
_paq.push(['enableLinkTracking']);
(function() {
var u="//piwik.example.com";
_paq.push(['setTrackerUrl', u+'piwik.php']);
_paq.push(['setSiteId', 1]);
var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s);
})();
</script>
This script will then include piwik.js
(basically this script) from your piwik installation on the page. piwik.js
records a couple of things (screen size, ip, etc.) and sends that to your piwik installation in a GET request, to register the pageview.
Now I don't understand why you would not just include piwik.js on your page straightaway. Why go through the trouble of fetching it from a separate location when you can just concatenate and minify it with the rest of your scripts?
It is possible to host piwik.js
on a cdn (see here and here), so I'm wondering why you wouldn't skip that step and concatenate it with the rest of your scripts and optimize from there?
Google analytics does the same thing I believe, so the answer doesn't need to be specific to Piwik as long as it applies to both.
This is to prevent the piwik.js file from blocking the rendering of the page. As you say, the snippet provided by Google Analytics works in much the same way. Steve Souders has a good write-up on the many benefits at http://www.stevesouders.com/blog/2009/12/01/google-analytics-goes-async/.
See also: http://googlecode.blogspot.nl/2009/12/google-analytics-launches-asynchronous.html
The second half of the snippet provides the logic that loads the tracking code in parallel with other scripts on the page. It executes an anonymous function that dynamically creates a element and sets the source with the proper protocol. As a result, most browsers will load the tracking code in parallel with other scripts on the page, thus reducing the web page load time.