Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does $(document).ready() fire?

The comments from this question got me thinking about something. When exactly does the $(document).ready() function fire? The obvious answer would be "when the document is ready," but when exactly is that?

For instance, if I turned output buffering on and flushed my output while PHP continued executing, wouldn't that send output to the browser? So is there any way the document could be ready before the PHP script has finished executing, or does the event wait until the request has finished?


EDIT:

The responses seem to basically agree that the event fires when the client thinks it's ready.

To get a better understanding (which I should have probably done in the first place), I just set up a test:

<?php ob_start(); ?>
<html>
<head>
    <script type="text/javascript" src="lib/js/jquery-1.7.1.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            alert("READY");
        });
    </script>
</head>
<body>
<?php
    ob_flush();
    for ($i=0; $i<999999; $i++) {
        echo "HELLO$i\n";
        ob_flush();
    }
?>
</body>
</html>

The result was that in this example, the contents began showing on the page right away, but the alert didn't happen until the loop was done, or the script timed out (30 seconds).

To the point of depending on which browser you use, I tried inserting this in my loop:

if ($i == 99) {
    echo "</body></html>";
}

And Chrome seemed to automatically correct it by putting those tags at the end of the page (as seen in the web dev inspector). Viewing the source of the page showed it in the middle, where I echo'ed it though.

like image 253
Travesty3 Avatar asked Jul 08 '13 18:07

Travesty3


People also ask

When does the document ready event occur?

Everything inside $ (document).ready () will load as soon as the DOM is loaded and before the page contents (html) are loaded. Show activity on this post. While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received.

Does the ready () method fire before images are loaded?

[...] The handler passed to .ready () is guaranteed to be executed after the DOM is ready [...] So yes, it may fire before images are loaded (that's what it's for, after all). It even adresses this explicitly:

What does $document ready do in HTML?

$(document).ready() The document ready event fired when the HTML document is loaded and the DOM is ready, even if all the graphics haven’t loaded yet. If you want to hook up your events for certain elements before the window loads, then $(document).ready is the right place.

Why won’t document ready work?

Why won't document.ready work? Show activity on this post. First it can be a conflict in jQuery. I always use "jQuery ()" instead of "$ ()" with SharePoint and jQuery.noConflict and make sure there is only 1 version of jQuery being loaded. Second the sequence of loading your script is important. Make sure it loads after jQuery is loaded.


2 Answers

jQuery's ready event for the document fires as soon as jQuery determines that the DOM is accessible. The exact mechanism depends on the browser.

Take a look at the relevant source code.

Firstly, there is a check to see if the DOM is already accessible at the point where an attempt was made to bind a listener to the event. If it is, the callbacks are scheduled to fire immediately - although they are not actually fired immediately, to allow the code already occupying the current execution slot to cancel the handlers if required.

If the DOM is not yet accessible, an attempt is made to bind an event listener to the browser's native DOMContentLoaded event - this is the "correct" native way to ask the browser to inform you when the DOM is available, but it's a relatively modern feature. If this is not possible (this almost certainly indicates you code is running in an older version of IE), the code falls back to a couple of mechanisms:

  • Try and attach to the onreadystatechange event of the document. This is not fool-proof and will be later than DOMContentLoaded would have been, but it's pretty good.
  • Fall back to the load event of the window object. This will often be much later than the DOM is available, but it's a last-ditch failsafe to ensure the event will always fire eventually.
  • The worst case scenario: keep polling the DOM until it's accessible.

From a PHP perspective, it is possible (but unlikely) for this to occur before your PHP script has finished executing. There are situations (such as long-polling) where the event would fire before your script is finished, but this would only occur in older browsers. However, in these scenarios, you wouldn't (shouldn't) be using these events at all, you would simply place the appropriate <script> elements in the body of the page to allow them to be executed as soon as they are loaded, without waiting for the rest of the DOM.

Personally, I never use any of these load-driven events, more or less for that reason. YMMV.

like image 93
DaveRandom Avatar answered Nov 06 '22 20:11

DaveRandom


For instance, if I turned output buffering on and flushed my output while PHP continued executing, wouldn't that send output to the browser?

Yes, it'd send output, but it doesn't mean the browser thinks the server has finished. I know it's not PHP, but I love the Perl article Suffering from Buffering. The document is ready when the UserAgent thinks it's ready. However, the browser will keep the socket open, while it still thinks it's receiving data and no END signal has been sent.

So is there any way the document could be ready before the PHP script has finished executing, or does the event wait until the request has finished?

Typically the browser will wait until the server finishes sending data. If you're flushing the output, it's possible the web server can timeout while the script is still running, for instance, I think Apache has a default of 2 minutes. If the server sends the end signal, your document has finished and your browser may prepare the DOM and fire the DOMReady event, even if your script is still running on the server.


Contrary to some other comments </body> and </html> are not good indicators of the DOM being ready, primarily because a page may be malformed (have misspellings or not include those end tags). In those cases, the browser will still render in Quirksmode and fire the DOMReady.

like image 35
vol7ron Avatar answered Nov 06 '22 21:11

vol7ron