Javascript Page Is Fully Loaded Boolean Check [Duplicate]

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?

3

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();
    }
  }
}

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.

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest