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

前端 未结 5 1751
栀梦
栀梦 2020-12-30 13:58

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

5条回答
  •  时光说笑
    2020-12-30 14:28

    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

提交回复
热议问题