- 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:
- open a url
- wait for the page to pletely load (scripts, images, etc)
- 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:
- open a url
- wait for the page to pletely load (scripts, images, etc)
- 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.
1 Answer
Reset to default 5Three options:
- If script is the last tag of the body, the DOM would be ready before script tag executes
- When the DOM is ready, "readyState" will change to "plete"
- 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');
});