What is the best and safest (not shortest/fastest) solution for (cross-browser/-platform) checking the existence of the document object (and maybe the window object if necessary)?
(function(root, undefined) {
var document = false;
if(typeof root.document === "object" && root.document !== null)
document = root.document;
// ...
if(document !== false)
doMyFancyClientSideStuff();
})(this);
Is typeof window.document in browsers always "object"? Or is there maybe anything like a work-around needed to make sure that our received object is really the DOM type of object, like window.document instanceof window.Document, and not just a self made object or what else.
Your definition of “Cross-Browser” is pretty cruicial here. I’d actually recommend to check for the
[[Class]]property like:That should return
[object HTMLDocument]in modern’ish browsers (or[object Undefined]). To also include IE8+ on this list, we need to callThis would create a list of
IE<8 will always return
[object]on thewindow.document[[Class]]. This is at least, the most accurate check I can think of. You can of course, also just check something likebut that is no guarantee that we are talking about an actuall DOM object, just that there is a property called
documentin the global object.