.ready()
JQ Home <<
Events <<
.ready()
DOM loaded event handler.
Description
The .ready()
method is used to specify a function to execute when the DOM has fully loaded.
- The
.ready()
method is similar to thewindow.onload
handler, but whereas the latter waits until all resources are loaded including all external resources, the.ready()
method is fired after the document is fully parsed and converted into the DOM tree. This can lead to significantly faster loading of our behaviour and therefore a richer experience for our users. - The other advantage that the
.ready()
method has over thewindow.onload
handler, is that it can be used multiple times within the same HTML document and the functions are executed in the order they are declared. - Any scripts placed in the
.ready()
method, that rely on the value of CSS style properties, should be placed in external stylesheets or embedded style elements ensuring their values are present before referencing the scripts. - The
.ready()
method is generally incompatible with the <body onload=""
> attribute so do not use the.ready()
method to attach load event handlers to the window or to more specific elements, like images when loaded assets are required. - The
.ready()
method can only be called on a jQuery object matching the current document, so selectors can be omitted.
Syntax
Signature | Description |
---|---|
.ready( handler ) | Specify a function to execute when the DOM has fully loaded. |
// Formal syntax
jQuery(document).ready(function(){
});
// Shorthand version (we mainly use this throughout the site)
$(function(){
});
Parameters
Parameter | Description | Type |
---|---|---|
handler | A function to execute. | Function |
Return
A jQuery
object.
.ready( handler )
Example
Events << Top
Specify a function to execute when the DOM has fully loaded.
In the example below we change all paragraph text to indigo once the DOM has fully loaded.
$(function(){
$('p').css('color', 'indigo');
});
Related Tutorials
jQuery Advanced Tutorials - Lesson 1 - Browser & Loading Events