I need to find out if the window has loaded or not.
I want to create a checkLoaded
function that will return true
or false
to indicate this, based on when I call it.
<html>
<head>
function checkLoaded(){
//alert true if window is loaded or alert false
}
</head>
<body onload="checkLoaded()"> <!-- This should alert true -->
Loding window.
<script>
checkLoaded();// this should alert false;
</script>
</body>
</html>
I don't want to use a global variable that I set when the window loads.
Is there any way that I can check the window
object's status, perhaps a property?
I don't want to use jQuery or any other external libraries.
Every JavaScript environment has a global object. Any variables that are created in the global scope are actually properties of this object, and any functions are methods of it. In a browser environment the global object is the window object, which represents the browser window that contains a web page.
The Window ObjectIt represents the browser's window. All global JavaScript objects, functions, and variables automatically become members of the window object. Global variables are properties of the window object. Global functions are methods of the window object.
You can use the document.readyState
property to check if the document has loaded without listening for any events. It will be set to "complete"
check if the document and all subresources are loaded. (This corresponds to the load
event.)
function checkLoaded() {
return document.readyState === "complete";
}
If you only want to check if the document has loaded, without worrying about subresources, you can also check if the property is "interactive"
.
function checkLoaded() {
return document.readyState === "complete" || document.readyState === "interactive";
}
This should work in current browsers, but is not supported in older versions of all browsers.
You have 2 events available:
addListener(document, "DOMContentLoaded", function(){}); //Dom parsing is finished
addListener(window, "load", function(){}); //loading of all external stuff is done
You can see a difference in those here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With