3

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

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.

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

nathancahill
  • 9,987
  • 9
  • 46
  • 90

2 Answers2

10

I would make use of 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();
    }
  }
}
berrberr
  • 1,824
  • 10
  • 16
8

You can check the document.readyState property.

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

Patrick Hofman
  • 148,824
  • 21
  • 237
  • 306