Why we Should Always Use Documnt.Ready() in jQuery

I will tell you why the use of Documnt.Ready() is a good practice in jQuery but before that I want to show you a small demo of code.

I will create a HTML page named "HtmlPage.html" with a TextBox like.

  1. <input id="Text1" type="text" /> 

Note

I am using the Visual Studio 2012 as the editor.



Download the jQuery library from the following links.

https://jquery.com/

Add the .js file in to the page as in the following:

  1. <script src="jquery-1.10.2.js"></script>; 

Add the following jQuery code to the body tag after the TextBox that will add the text to the TextBox.

  1. <script type="text/javascript">  
  2.         ("#Text1").val("This is my textbox");          
  3. </script> 



And result will be look like:



But what will happen if I write the jQuery code before the TextBox as in the following?

  1. <body>        
  2.     <script type="text/javascript">           
  3.          $("#Text1").val("This is my textbox");           
  4.     </script>  
  5.     <input id="Text1" type="text" />        
  6. </body> 

As you can see in the following result there is no text set in the TextBox:



But the question is "Why the TextBox is blank this time".

Answer

jQuery didn't get the TextBox control, that's why the TextBox didn't set the value.

To understand why jQuery didn't get the TextBox control, you need to be familiar with execution of the Data Object Model (DOM).

“The data object model loads the code of the HTML page into memory line-by-line or sequentially, so it didn't understand the TextBox control when I wrote the code of jQuery to set the value of TextBox because the control was not yet loaded into memory.”

Solution

To resolve this situation always use the Documnt.Ready() function that will execute the code after the document is ready after loading.

  1. <body>          
  2.     <script type="text/javascript">           
  3.          $(document).ready(function () {  
  4.              $("#Text1").val("This is my textbox");  
  5.          });  
  6.     </script>  
  7.     <input id="Text1" type="text" />        
  8. </body 

Tip: Always write the JavaScript or jQuery code in a single place and especially in the head tag that will separate it from the body tag.