Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if document is ready?

Tags:

How to check if document is ready (all js files loaded, DOM is ready) through jQuery? Is there any flag?

Facing issues if some of the files are not downloaded completely, and the event is raised by user. I want to check inside event handler.

I am using jQuery, asp.net

like image 783
Lalit Avatar asked May 12 '10 14:05

Lalit


People also ask

Where is the document ready function?

So technically it doesn't matter where you put it. Many people like putting script in the head, because it makes sure the script is read before the page is loaded. Other people like putting it at the very end (just before the end body tag) so that all of the elements of the page are loaded before the script reads them.

How do I use document ready?

$( document ). ready()A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ). ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside $( window ).

How can you tell if a page is fully loaded?

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.


1 Answers

This isn't documented, I don't think, but if you look at the jQuery code for $(document).ready:

// If the DOM is already ready if ( jQuery.isReady ) {   // Execute the function immediately   fn.call( document, jQuery ); } // ... 

Thus, for a way that may change, you can use $.isReady or jQuery.isReady.

A better way would be to use $(document).ready in line. e.g.:

function myClickHandler(event) {   // do stuff    $(document).ready(function() {     // Do this immediately if DOM is loaded, or once it's loaded otherwise.   } } 

Essentially, this uses the ready function as a guard. Instead of an if statement, you use the ready function. Of course, the ready function has the behavior that it will run once the DOM is loaded. If your behavior is only wanting something to happen if it's loaded, but never doing it if the DOM isn't loaded yet, then using the flag above, or setting your own, is the better way to go. Setting your own:

$(document).ready(function() {   window.domIsReady = true; }  if (window.domIsReady) {   // do stuff } 

Creating your own is probably better, since jQuery.isReady doesn't seem to be documented, and therefore probably isn't supported and may be changed at any time.

like image 187
Antonio Salazar Cardozo Avatar answered Sep 26 '22 02:09

Antonio Salazar Cardozo