Javascript 在不使用任何全局变量的情况下确定窗口是否已加载
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11528132/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Determining whether the window has loaded without using any global variables
提问by gaurang171
I need to find out if the window has loaded or not.
我需要找出窗口是否已加载。
I want to create a checkLoaded
function that will return true
or false
to indicate this, based on when I call it.
我想创建一个checkLoaded
函数,该函数将根据我调用它的时间返回true
或false
表明这一点。
<html>
<head>
function checkLoaded(){
//alert true if window is loaded or alert false
}
</head>
<body onload="checkLoaded()"> <!-- This should alert true -->
Loding window.
<script>
checkLoaded();// this should alert false;
</script>
</body>
</html>
I don't want to use a global variable that I set when the window loads.
我不想使用在窗口加载时设置的全局变量。
Is there any way that I can check the window
object's status, perhaps a property?
有什么方法可以检查window
对象的状态,也许是属性?
I don't want to use jQuery or any other external libraries.
我不想使用 jQuery 或任何其他外部库。
回答by Facebook Staff are Complicit
You can use the document.readyState
property to check if the document has loaded without listening for any events. It will be set to "complete"
check if the document and all subresources are loaded. (This corresponds to the load
event.)
您可以使用该document.readyState
属性来检查文档是否已加载,而无需侦听任何事件。它将被设置为"complete"
检查文档和所有子资源是否已加载。(这与load
事件相对应。)
function checkLoaded() {
return document.readyState === "complete";
}
If you only want to check if the document has loaded, without worrying about subresources, you can also check if the property is "interactive"
.
如果只想查看文档是否加载,不关心子资源,也可以查看属性是否为"interactive"
.
function checkLoaded() {
return document.readyState === "complete" || document.readyState === "interactive";
}
This should work in current browsers, but is not supported in older versions of all browsers.
这应该适用于当前浏览器,但不支持所有浏览器的旧版本。
回答by Grzegorz Kaczan
回答by acondolu
Maybe simply something like this:
也许只是这样:
<html>
<script>
var loaded = false;
? function checkLoaded(){
alert(window.loaded);
? }
</script>
<body onload="window.loaded = true; checkLoaded()">
? ?Loading window.
?<script>
checkLoaded();
</script>
</body>
</html>
回答by Paul
This will alert when the window is loaded:
这将在窗口加载时发出警报:
(function(w) {
//private variable
var loaded = false;
w.onload = function() {
loaded = true;
};
w.checkLoaded = function() {
alert(loaded);
};
})(window);
You can now call checkLoaded()
from any part of your app and it will return true or false.
您现在可以checkLoaded()
从应用程序的任何部分调用,它会返回 true 或 false。