TYPKRFT
TYPKRFT

Reputation: 326

How should I wait for the document to load?

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 completely load (scripts, images, etc)
  3. check if page loaded is true.

From my understanding I would do something like this:

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

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

isLoaded()

The problem:

Upvotes: 2

Views: 6747

Answers (1)

Mouaici_Med
Mouaici_Med

Reputation: 410

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 "complete"
  3. Put everything under 'DOMContentLoaded' event listener.

onreadystatechange

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

DOMContentLoaded

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

Upvotes: 5

Related Questions