What Is Document Ready Event In JQuery ???

What is the role of below code in JQuery? For me it is always be part of understanding JQuery fundamentals

$(document).ready(function(){
   // jQuery methods go here...
});

Lets run below sample code and you wonder!!!
Why we get first alert “Alert 2” and second alert “Alert 1”
Interesting !!! Correct…

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  alert("Alert 1");
});
alert("Alert 2");
</script>
</head>
<body></body>
</html>

Reason…guess????

$(document).ready(function(){
   // jQuery methods go here...
});

This code prevent any jQuery code from running before the document is finished loading (is ready).Good practice is to wait for the document to be fully loaded and ready before start working with it. This also allows developer to have JavaScript code before the body of document, in the head section.

Here are few examples of actions that can fail if methods run before the document is fully loaded:

  • Trying to hide an element that is not created yet
  • Trying to get the size of an image that is not loaded yet

Note: JQuery team has also made an even shorter method for the document ready event:

$(function(){
   // jQuery methods go here...
});
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s