Determining if a window has loaded without using any global variables

I need to find out if the window is 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 do not want to use the global variable that I set when the window loads.

Is there a way to check the status of a window object, possibly a property?

I do not want to use jQuery or any other external libraries.

+6
source share
5 answers

You can use the document.readyState property to check if a document is loaded without listening to any events. It will be set to "complete" to check if the document and all sub resources are loaded. (This corresponds to the load event.)

 function checkLoaded() { return document.readyState === "complete"; } 

If you only want to check if the document is loaded without worrying about sub-resources, you can also check if there is an "interactive" property.

 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.

+21
source

This will be displayed when the window loads:

 (function(w) { //private variable var loaded = false; w.onload = function() { loaded = true; }; w.checkLoaded = function() { alert(loaded); }; })(window); 

Now you can call checkLoaded() from any part of your application, and it will return true or false.

+1
source

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 the difference in here

+1
source

Maybe just something like this:

 <html> <script> var loaded = false; function checkLoaded(){ alert(window.loaded); } </script> <body onload="window.loaded = true; checkLoaded()">  Loading window. <script> checkLoaded(); </script> </body> </html> 
+1
source

Does it help?

 <script> var loaded = false; function checkLoaded(){ alert(loaded); //alert true if window is loaded or alert false } </script> <body onload="loaded = true;checkLoaded();"> <!-- This should alert true --> Loding window. <script> checkLoaded();// this should alert false; </script> </body> 
0
source

Source: https://habr.com/ru/post/920717/


All Articles