8

我一直在对 window.document 对象进行一些研究,以确保我的 JavaScript 解决方案之一是可靠的。是否存在 window.document 对象为 null 或未定义的情况?

为了讨论,这里有一段不相关的示例代码。是否有任何情况下这段代码会失败(也就是抛出异常)?

$(document).ready(function() {
    var PageLoaded = (window.document.readyState === "complete");
});
4

4 回答 4

4

是否存在 window.document 对象为 null 或未定义的情况?

是的,对于不在文档中的 JavaScript 代码(例如 node.js)。但是这样的代码也可能没有窗口对象(尽管它会有一个全局对象)。

对于符合 W3C DOM 的用户代理中的 HTML 文档中的代码,没有。

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

它会在以下位置失败:

  1. jQuery 就绪功能失败(可能至少在某些浏览器中,但不是桌面和某些移动设备流行使用的浏览器),
  2. 没有window object,或
  3. 没有window.document对象

为了确保代码在各种主机中工作,您可以执行以下操作:

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

这并不需要额外编写,并且可能只需要完成一次。

备择方案:

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

(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));
于 2012-08-25T13:24:59.160 回答
1

我认为文档总是被定义的,因为浏览器向您显示的所有内容都是 html 文档,甚至site is not available. 更多,document是只读属性

window.document = null; 
console.log(window.document); //Document some.html#
于 2012-08-25T03:45:45.667 回答
1

忽略 Javascript 在 Web 浏览器/用户代理之外的其他地方运行的事实,您的 pageLoaded 测试可能会在 iframe 上失败(未经测试,但我知道它们会变得很奇怪)。

可能还有一些关于“页面加载”是什么意思的问题。您是否正在尝试查看 DOM 是否已呈现并且元素是否已准备好进行操作?或者您是否正在检查页面加载是否确实完成,其中包括加载所有其他元素,例如图形。

这个讨论可能很有用: How to check if DOM is ready without a framework?

于 2012-08-25T03:47:13.957 回答
0

因为你的javascript代码必须写在html文档中,所以你的代码不能在文档外执行,换句话说,没有文档,就没有javascript。

于 2012-08-25T04:53:33.520 回答