Is window.document ever null or undefined?

后端 未结 4 798
梦谈多话
梦谈多话 2020-12-06 02:56

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

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-06 03:03

    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:

    1. the jQuery ready function fails (likely in at least some browsers, though not the ones in popular use for desktop and some mobile devices),
    2. there is no window object, or
    3. there is no window.document object

    To 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));
    

提交回复
热议问题