jQuery document.ready function: When and why to use it

Why using document.ready function in jQuery

In order to ensure that jQuery code executes, the whole page elements or document should be loaded properly or otherwise, the code may not execute properly.

To ensure that the document is loaded fully, the jQuery provides a method to detect this state. The method is the document.ready which syntax and examples are shown below.

Syntax of document.ready jQuery

Following is the syntax to use document.ready function:


An example of document.ready

Where jQuery document.ready statement means the document is ready to execute JavaScript/jQuery code. This might be required in scenarios like hiding some data and only showing when the user clicks, getting image sizes etc. The document.ready function would allow your JS code to be in the header section of the document.

Example of using jQuery document ready

Following example shows how to include the document.ready jQuery function in your web pages. Generally, you will place the jQuery document.ready statement just after the <script> opening tag as follows:

Experience this example online

Another example of document.ready function

In this example, the document.ready function is used with the append method of jQuery. The function is used just after the <script> tag. See the example by clicking the link below:

Experience this example online


Also see jQuery append