确定窗口是否已加载而不使用任何全局变量 [英] Determining whether the window has loaded without using any global variables

查看:139
本文介绍了确定窗口是否已加载而不使用任何全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要找出窗口是否加载。



我想创建一个 checkLoaded 函数将返回 true false ,以根据何时调用它来指示。

 < html> 
< head>
函数checkLoaded(){
//如果窗口加载或警报为false,则返回true true
}
< / head>
< body onload =checkLoaded()> <! - 这应该提醒true - >
编码窗口。
< script>
checkLoaded(); //这应该提醒false;
< / script>
< / body>
< / html>

我不想使用在窗口载入时设置的全局变量。



有什么办法可以检查窗口对象的状态,也许是一个属性?



我不想使用jQuery或任何其他外部库。

解决方案

您可以使用 document.readyState 属性来检查文档是否加载而不监听任何事件。它将被设置为完成检查文档和所有子资源是否已加载。 (这对应于加载事件。)

  function checkLoaded() {
return document.readyState ===complete;
}

如果您只想检查文档是否加载,而不必担心子资源您还可以检查该属性是否为interactive

  function checkLoaded(){
return document.readyState ===complete|| document.readyState ===interactive;
}

这应该在当前浏览器中工作,但在旧版本的所有浏览器。


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.

<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?

I don't want to use jQuery or any other external libraries.

解决方案

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.)

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".

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.

这篇关于确定窗口是否已加载而不使用任何全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆