最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How should I wait for the document to load? - Stack Overflow

programmeradmin2浏览0评论
  • Forgive me I am new to javascript.

I am trying to figure out the best approach to wait for a document to load.

What I am trying to do:

  1. open a url
  2. wait for the page to pletely load (scripts, images, etc)
  3. check if page loaded is true.

From my understanding I would do something like this:

window.location = ""

function isLoaded() {
  while (document.readyState != "plete") {
  }
  return true;
}

isLoaded()

The problem:

  • When I do this in Firefox's console. I get true - I believe - before the document has tried to open the page, or I get a "busy script" warning if I try to run it from the console after the current page is no longer on the screen.
  • Maybe I am doing it wrong, maybe there is a better way to test, I am not sure.
  • Little background. I am trying to write an Add On for Firefox, so my script will be run on the page and not part of the page. If that helps.
  • Forgive me I am new to javascript.

I am trying to figure out the best approach to wait for a document to load.

What I am trying to do:

  1. open a url
  2. wait for the page to pletely load (scripts, images, etc)
  3. check if page loaded is true.

From my understanding I would do something like this:

window.location = "https://somewebsite."

function isLoaded() {
  while (document.readyState != "plete") {
  }
  return true;
}

isLoaded()

The problem:

  • When I do this in Firefox's console. I get true - I believe - before the document has tried to open the page, or I get a "busy script" warning if I try to run it from the console after the current page is no longer on the screen.
  • Maybe I am doing it wrong, maybe there is a better way to test, I am not sure.
  • Little background. I am trying to write an Add On for Firefox, so my script will be run on the page and not part of the page. If that helps.
Share Improve this question edited Mar 2, 2017 at 20:15 TYPKRFT asked Mar 2, 2017 at 19:53 TYPKRFTTYPKRFT 3265 silver badges14 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

Three options:

  1. If script is the last tag of the body, the DOM would be ready before script tag executes
  2. When the DOM is ready, "readyState" will change to "plete"
  3. Put everything under 'DOMContentLoaded' event listener.

onreadystatechange

  document.onreadystatechange = function () {
     if (document.readyState == "plete") {
     // document is ready. Do your stuff here
   }
 }

DOMContentLoaded

document.addEventListener('DOMContentLoaded', function() {
   console.log('document is ready. I can sleep now');
});
发布评论

评论列表(0)

  1. 暂无评论