Javascript 页面是否完全加载布尔检查

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24947837/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 03:38:44  来源:igfitidea点击:

Javascript page is fully loaded boolean check

javascript

提问by nathancahill

Short of setting a variable inside of window.onload, is there a way to detect if the page has finished loading?

没有在 中设置变量window.onload,有没有办法检测页面是否已完成加载?

I'm injecting a bit of third party JS in a page that may or may not be fully loaded. I can't modify the page. I can't use JQuery.

我在一个页面中注入了一些第三方 JS,这个页面可能会也可能不会完全加载。我无法修改页面。我不能使用 JQuery。

I can add a function and poll it repeatedly until it returns true (page fully loaded). Any ideas?

我可以添加一个函数并重复轮询它,直到它返回 true(页面完全加载)。有任何想法吗?

回答by Patrick Hofman

You can check the document.readyStateproperty.

你可以document.readyState查房。

From MDN:

来自 MDN:

Returns "loading" while the document is loading, "interactive" once it is finished parsing but still loading sub-resources, and "complete" once it has loaded.

在文档加载时返回“正在加载”,在完成解析但仍在加载子资源后返回“交互”,并在加载后返回“完成”

回答by berrberr

I would make use of readyState.

我会使用readyState

For example first check if the document is loaded, and if not set up a listener:

例如首先检查文档是否加载,如果没有设置监听器:

if(document.readyState === 'ready' || document.readyState === 'complete') {
  doSomething();
} else {
  document.onreadystatechange = function () {
    if (document.readyState == "complete") {
      doSomething();
    }
  }
}