What is the difference between using document.head
and using document.getElementsByTagName(\"head\")[0]
? Tests I ran showed that they both take about a
This is more of a convenience matter than a performance one (though document.head
should have a negligible benefit). Use which ever you like, or, use one as a fallback to the other (as your example code does). Having the fallback is wise, since document.head
is not support in IE 6-8.
It's not likely that getElementsByTagName
will soon be deprecated, so this isn't a great example of when it's good to provide a fallback. You could safely use the more verbose route on its own and enjoy support on into the future.
Better examples of these types of things would be events, and how they're passed around in modern browsers, compared to older browsers. It is not uncommon to see something like this:
function callback (event) {
var id = (event || window.event).target.id;
}
In this case though, the window.event
portion is necessary for legacy support. If the event
object is undefined
, we assume the event is a member on the window
object. As browsers mature, window.event
ceases to be a thing, and these tests unanimously return event.target.id
instead.
Again, your case is a bit different as getElementsByTagName
will likely never be deprecated or vanish as window.event
did.