What’s the point of document.defaultView?
In browsers returns the window object associated with the document or null if none available.
Code like the following (from PPK’s site) makes use of document.defaultView:
function getStyle(el,styleProp)
{
var x = document.getElementById(el);
if (x.currentStyle)
var y = x.currentStyle[styleProp];
else if (window.getComputedStyle)
var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
return y;
}
Code like this can be found in other places, like David Mark’s My Library. I’m not sure if people are just copying from PPK or some other source or coming up with this independently, but I don’t understand it.
My question is, what is the point of using document.defaultView in cases like this? Wouldn’t it be easier to write this as follows:
function getStyle(element, styleProp) {
if (element === ''+element) element = document.getElementById(element);
return element.currentStyle ? element.currentStyle[styleProp] :
getComputedStyle(x,null).getPropertyValue(styleProp);
}
What does document.defaultView.getComputedStyle do that window.getComputedStyle or simply getComputedStyle does not?
cwolves’ answer got me thinking in the right direction. The original function is silly, missing the point of defaultView. My proposal above is less silly, but also missing the point of defaultView. Here’s my new proposal:
function getStyle(element, styleProp) {
var view = element.ownerDocument && element.ownerDocument.defaultView ?
element.ownerDocument.defaultView : window;
return view.getComputedStyle ?
view.getComputedStyle(element,null).getPropertyValue(styleProp) :
element.currentStyle ?
element.currentStyle[styleProp] : null;
}
The element itself must be passed in, not the id. I think this is probably to be preferred anyway. This gets the document containing the node, and the window associated with it. It has a fallback to the current window’s getComputedStyle if ownerDocument or defaultView are broken (I vaguely remember getComputedStyle being around before defaultView). This is probably closer to the intended use of defaultView.
I’m not positive on this, but I imagine that it’s the result of fixing a bug from either trying to run code on a detached document (i.e. something that exists in memory but is not in the page) or trying to run on a document in a different window (e.g. an iframe or a popup).
According to your quote, when
document.defaultViewis run on a document that is NOT the current document, you will get the associated window object, thusdocument.documentView.getComputedStyle !== getComputedStylesince they are in different contexts.In short, I believe it’s akin to
document.windowwhich doesn’t exist.