我一直在对window.document对象进行一些研究,以确保我的一个JavaScript解决方案是可靠的.是否存在window.document对象为null或未定义的情况?
为了便于讨论,这里是一段不相关的示例代码.是否有任何情况下这段代码会失败(又称抛出异常)?
$(document).ready(function() {
var PageLoaded = (window.document.readyState === "complete");
});
Run Code Online (Sandbox Code Playgroud)
是否存在 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]
Run Code Online (Sandbox Code Playgroud)
它将在以下位置失败:
window object
, 或window.document
对象为了确保代码在各种主机上运行,您可以执行以下操作:
if (typeof window != 'undefined' && window.document &&
window.document.readyState == whatever) {
// do stuff
}
Run Code Online (Sandbox Code Playgroud)
这不需要写太多额外的内容,并且可能只需要完成一次。
备择方案:
(function (global) {
var window = global;
if (window.document && window.document.readyState == whatever) {
// do stuff
}
}(this));
Run Code Online (Sandbox Code Playgroud)
和
(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));
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
17936 次 |
最近记录: |