jQuery documentready

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 documentready

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

1 Default jQuery documentready

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 documentready

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 documentready

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

1 Example jQuery documentready 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.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  alert("The document has been fully loaded.");
});
</script>
</head>
<body>

<p>Learn jQuery document ready.</p>

</body>
</html>

2 Example jQuery documentready Using concise syntax

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

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
  $(function(){
    alert("The document has been fully loaded.");
  });
</script>
</head>
<body>
  <p>Learn jQuery document ready.</p>
</body>
</html>

Conclusion

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