Is window.document ever null or undefined?

I did some research on the window.document object to make sure that one of my JavaScript solutions is reliable. Is there ever a case where the window.document object is null or undefined?

For discussion purposes, here is an example of non-relevant code example. Are there situations in which this piece of code will fail (for example, an exception)?

$(document).ready(function() { var PageLoaded = (window.document.readyState === "complete"); }); 
+8
javascript dom
source share
4 answers

Is there ever a case where the window.document object is null or undefined?

Yes, for JavaScript code that is not in the document (e.g. node.js). But such code may not have a window object (although it will have a global object).

For code in HTML documents, user agents that are compatible with the W3C DOM are not.

 > Are there any situations in which this piece of code will fail (ie throw > an exception)? > > [snip jQuery code] 

This will fail if:

  • jQuery ready function does not work (probably, at least in some browsers, although not in popular use for desktop computers and some mobile devices),
  • no window object or
  • no window.document object

To make sure that the code runs on different hosts, you can do something like:

  if (typeof window != 'undefined' && window.document && window.document.readyState == whatever) { // do stuff } 

which is not much to write, and probably only needs to be done once.

Alternative:

 (function (global) { var window = global; if (window.document && window.document.readyState == whatever) { // do stuff } }(this)); 

and

 (function (global) { var window = global; function checkState() { if (window.document && window.document.readyState) { alert(window.document.readyState); } else { // analyse environment } } // trivial use for demonstration checkState(); setTimeout(checkState, 1000); }(this)); 
+4
source share

I think a document is always defined because the entire browser shows that you are an html document, even site is not available . More details, document - readonly property

 window.document = null; console.log(window.document); //Document some.html# 
+1
source share

Ignoring the fact that Javascript launches other places besides web browsers / user agents, your test on the Loaded page may fail in the iframe (unchecked, but I know they are weird).

You may also wonder what the "loaded page" means. Are you trying to see if a DOM has been provided and the elements are ready to be manipulated? Or you check if the page is really loaded, which also includes all the other elements, such as graphics.

This discussion may be useful: How to check if the DOM is ready without a frame?

+1
source share

Because your javascript code must be written in an html document, so your code cannot be executed from a document, in other words, without a document, without javascript.

+1
source share

All Articles