I noticed that the Piwik tracking code inserts the script tag before the first script tag in the <head>
:
var d=document,
g=d.createElement('script'),
s=d.getElementsByTagName('script')[0];
...
s.parentNode.insertBefore(g,s);
Is there a reason for this? Can I just insert it at the end of <head>
or even in the body?
Yes, you could insert it wherever you want. When a script does something like this, it's considered a nice thing. It's going to put it in the same location as the first script on your page, which is presumably where the page author wanted his scripts to be placed. If the first script is in the <head>
or <body>
that's where it'll put it.
There's no real reason, and also, no real benefit to the script itself either. The very fact that it's loading an external resource means that it's execution will be after the page has finished loading and executing the scripts that were hardcoded in the page (due to JS's single-threaded nature and the fact that loading a script like this will cause it to behave in an async
fashion).
Basically you can have it load wherever you want, but presumably it's not going to benefit you, page loading speed, or the script itself.