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
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:
onreadystatechange
event of the document. This is not fool-proof and will be later than DOMContentLoaded
would have been, but it's pretty good.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.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 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.