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 {
Robg
source share