views:

70

answers:

1

Every browser I've observed creates a <head> element that's accessible in the DOM even if there are no explicit <head></head> tags in the document's markup.

However, Google Analytics uses the following code for dynamic script insertion:

(function() {
  var ga = document.createElement('script');
  ga.type = 'text/javascript';
  ga.async = true;
  ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
  (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ga);
})();

The following line:

(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ga);

seems to make a special concession for cases where a <head> element is not present.

Is this just a case of extreme backwards-compatibility (e.g., for Netscape 4, or the like), or is there a case to be made for not assuming that modern browsers (i.e., Internet Explorer 6 and more recent) will always have access to a <head> element in the DOM?

+6  A: 

The modern browsers are creating the head element for you when needed.

But assuming that the client will do so is not smart if you want your code to be bullet-proof. So the Googlers are being conservative and safe.

The extra clause in their statement is de minimus, but adds additional reliability. So it's a good thing.

ps Good job on the question and pulling out the relevant code.

Added:

The HTML spec says that the head tag is optional. I don't think the browers' creation of the head "element" in the dom is required by the spec. Google doesn't want to (and shouldn't) count on it being there.

Larry K
The HTML 4.01 spec says that the head *element* is required. Only the *tags* are optional. See http://www.w3.org/TR/1999/REC-html401-19991224/struct/global.html#edef-HTML . Browsers, of course, frequently do not follow the specs and if they consistently automagically create the head element, it'll be because significant numbers of real world web pages break in browsers that don't do so.
Alohci
@Alochi -- thank you for the ref. I've updated the answer.
Larry K
@Larry: Good answer! Thanks very much for your help.@Alohci: Thanks for the extra input - that makes sense.
Bungle