jQuery $(document).ready()

jQuery $(document).ready() is used to execute a function when the HTML document is fully loaded.

Making sure that the HTML document is fully loaded ensures that the JavaScript statements that you intended for some of the HTML elements are loaded first. If you do not wait for the HTML element to load, but run a JavaScript statement on the element, nothing happens, and moreover this behavior is unpredictable.

So, when your JavaScript functions are intended for elements in the HTML document, which is the case most of the times, wait for the document to fully load first.

Syntax – jQuery $(document).ready()

The syntax to use jQuery $(document).ready() method is given below.

ADVERTISEMENT

1. Default jQuery $(document).ready()

To execute a function when the HTML document is loaded completely in a browser window,

$(document).ready(function(){
  // write your code here
});

2. Concise jQuery $(document).ready()

You can also use a concise version of $(document).ready() method provided below. Note that the following syntax also mean $(document).ready().

$(function(){
  // write your code here
});

Examples – jQuery $(document).ready()

Following examples help you understand the usage of jQuery $(document).ready() method :

1. Example – jQuery $(document).ready() – Basic Usage

Following is a basic example to learn the usage of $(document).ready() method. The function in the ready() method contains an alert() method to display a message.

2. Example – jQuery $(document).ready() – Using concise syntax

Following is a basic example to learn the usage of concise version of $(document).ready() method.

Conclusion

In this jQuery Tutorial, we have learnt jQuery $(document).ready() method : Syntax and Usage with examples.