The answers given as far as now focus two different aspects and are both very useful.
If portability is a requirement for you, in documents not under your ownership where you can't control the DOM coherence, it may be useful to check for the existence of the element you have to append the script to; this way, it will works also when the HEAD section has not been explicitly created:
var script = document.createElement('script');
var parent = document.getElementsByTagName('head').item(0) || document.documentElement;
parent.appendChild(script);
Apart of CORS policy and other easily detectable logic errors, I don't see cases in which this DOM manipulation task should fail, so checking for document.body
as a fallback is not necessary by my point of view.
As other users outlined too, document.head
was not widely supported yet, at the time the question was posted, as it is a HTML5 spec, while document.body
is, that's why you saw the latter working on all the browsers.
So you could get the HEAD with:
document.head || document.getElementsByTagName('head').item(0)
but I don't see it very useful, as the latter won't ever be wrong and is a readable and standard DOM query, unless you find out that document.head
is faster from a performance perspective.
Another possible advantage I can see about this form is a code transition from older JavaScript to a more modern HTML5 compliant code, brief and more readable.
If compatibility is a must, you could use tricks adopted by libraries for which portability is mandatory (e.g. solutions from Google, Yandex and others):
var parent = document.getElementsByTagName('head')[0] || document.documentElement.firstChild;
parent.appendChild(script);
This way, in the improbable case the HEAD element does not exist while the BODY (or another element) does, you are sure to append the script to it.
I also add a useful bit: the HTTP request of the script source is sent from the browser when the src
attribute is set and it is appended to the DOM. No matter in which order these two conditions are met, the last of these two events causes the HTTP request to be dispatched.