title: When does $(document).ready() fire?
body: <p>The comments from <a href="https://stackoverflow.com/q/17532656/259457">this question</a> got me thinking about something. When exactly does the <code>$(document).ready()</code> function fire? The obvious answer would be "when the document is ready," but when exactly is that?</p>
  
  <p>For instance, <a href="https://stackoverflow.com/q/4235323/259457">if I turned output buffering on and flushed my output while PHP continued executing</a>, 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?</p>
  
  <hr />
  
  <p><strong>EDIT:</strong></p>
  
  <p>The responses seem to basically agree that the event fires when the client thinks it's ready.</p>
  
  <p>To get a better understanding (which I should have probably done in the first place), I just set up a test:</p>
  
  <pre><code>&lt;?php ob_start(); ?&gt;
  &lt;html&gt;
  &lt;head&gt;
      &lt;script type="text/javascript" src="lib/js/jquery-1.7.1.min.js"&gt;&lt;/script&gt;
      &lt;script type="text/javascript"&gt;
          $(document).ready(function() {
              alert("READY");
          });
      &lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
  &lt;?php
      ob_flush();
      for ($i=0; $i&lt;999999; $i++) {
          echo "HELLO$i\n";
          ob_flush();
      }
  ?&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>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).</p>
  
  <p>To the point of depending on which browser you use, I tried inserting this in my loop:</p>
  
  <pre><code>if ($i == 99) {
      echo "&lt;/body&gt;&lt;/html&gt;";
  }
  </code></pre>
  
  <p>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.</p>