.ready( handler )Возвращает: jQuery
Описание: Specify a function to execute when the DOM is fully loaded.
Добавлен в версии: 1.0.ready( handler )
handlerТип: Function()A function to execute after the DOM is ready.
Most browsers provide similar functionality in the form of a
DOMContentLoaded event. However, jQuery's
.ready() method differs in an important and useful way: If the DOM becomes ready and the browser fires
DOMContentLoaded before the code calls
.ready( handler ), the function
handler will still be executed. In contrast, a
DOMContentLoaded event listener added after the event fires is never executed.
Browsers also provide the
load event on the
window object. When this event fires it indicates that all assets on the page have loaded, including images. This event can be watched in jQuery using
$( window ).on( "load", handler ). In cases where code relies on loaded assets (for example, if the dimensions of an image are required), the code should be placed in a handler for the
load event instead.
Note that although the DOM always becomes ready before the page is fully loaded, it is usually not safe to attach a
load event listener in code executed during a
.ready() handler. For example, scripts can be loaded dynamically long after the page has loaded using methods such as
$.getScript(). Although handlers added by
.ready() will always be executed in a dynamically loaded script, the
load event has already occurred and those listeners will never run.
jQuery offers several ways to attach a function that will run when the DOM is ready. All of the following syntaxes are equivalent:
$( handler )
$( document ).ready( handler )
$( "document" ).ready( handler )
$( "img" ).ready( handler )
$().ready( handler )
As of jQuery 3.0, only the first syntax is recommended; the other syntaxes still work but are deprecated. This is because the selection has no bearing on the behavior of the
.ready() method, which is inefficient and can lead to incorrect assumptions about the method's behavior. For example, the third syntax works with
"document" which selects nothing. The fourth syntax waits for the document to be ready but implies (incorrectly) that it waits for images to become ready.
There is also
$(document).on( "ready", handler ), deprecated as of jQuery 1.8 and removed in jQuery 3.0. Note that if the DOM becomes ready before this event is attached, the handler will not be executed.
.ready() method is typically used with an anonymous function:
Which is equivalent to the recommended way of calling:
Aliasing the jQuery Object
$.noConflict() is used to avoid namespace conflicts, the
$ shortcut is no longer available. However, the
.ready() handler is passed a reference to the
jQuery object that called the method. This allows the handler to use a jQuery object, for example as
$, without knowing its aliased name:
Display a message when the DOM is loaded.