I've been doing some research on the window.document object in order to make sure one of my JavaScript solutions is reliable. Is there ever a case when the window.document object is null or undefined?
For the sake of discussion here's a non-relevant example piece of code. Are there any situations in which this piece of code will fail (aka, throw an exception)?
$(document).ready(function() {
var PageLoaded = (window.document.readyState === "complete");
});
You can use the qualities of the abstract equality operator to do this: if (variable == null){ // your code here. } Because null == undefined is true, the above code will catch both null and undefined .
It means null is equal to undefined but not identical. When we define a variable to undefined then we are trying to convey that the variable does not exist . When we define a variable to null then we are trying to convey that the variable is empty.
Code that runs without 'onclick'.
Is there ever a case when the window.document object is null or undefined?
Yes, for JavaScript code that isn't in a document (e.g. node.js). But such code may not have a window object either (though it will have a global object).
For code in HTML documents in user agents compliant with the W3C DOM, no.
> Are there any situations in which this piece of code will fail (i.e. throw
> an exception)?
>
> [snip jQuery code]
It will fail where:
window object
, orwindow.document
objectTo be confident of code working in a variety of hosts, you can do something like:
if (typeof window != 'undefined' && window.document &&
window.document.readyState == whatever) {
// do stuff
}
which isn't much extra to write, and likely only needs to be done once.
Alternatives:
(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));
I think document is always defined, cause all that browser shows you is a html-document, even site is not available
. More, document
is readonly property
window.document = null;
console.log(window.document); //Document some.html#
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With