4

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
  • 10,452
  • 9
  • 51
  • 91

2 Answers2

14

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,914
  • 11
  • 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
  • 153,850
  • 22
  • 249
  • 325