Need for jquery document ready()
We are going to find out the need of jquery document ready. Take a look at the following code, you may expect the list item color will be changed to blue color. But the color will remain the same. Because at the time of the script executed the DOM is not fully ready, and the script won’t find the (‘ul li’) element in the DOM. Here comes jquery document ready() method.
<html>
<head>
<title>Jquery Document ready() Tutorial</title>
<style type="text/css">
ul li{color: green;}
</style>
<script src="jquery-1.8.3.js"></script>
<script>
$('ul li').css('color','blue');
</script>
</head>
<body>
<ul>
<li>Title 1</li>
<li>Title 2</li>
<li>Title 3</li>
</ul>
</body>
</html>
jquery document ready() – Executing code when the DOM is ready, but before window.onload
The actual javascript event window.onload used to manage a web page which has been fully loaded. But the problem is window.onload event will be fired only after all assets including images, flash, etc are loaded, therefore waiting around for this event will be somewhat time consuming.
A much better alternative will be to begin scripting the actual DOM once it is available to become manipulated. jQuery offers a custom made event which is performed as soon as the DOM is available to be scripted however before the actual window.onload event fires.
<script>
$(document).ready(function(){
$('ul li').css('color','blue');
});
</script>
Shorthand of jquery document ready(), but same as the above code.
<script>
$(function(){
$('ul li').css('color','blue');
});
</script>
Ensure that all stylesheets are attached well before the jQuery code. Doing this will ensure all of the components within the DOM are properly rendered well before jQuery starts executing code.
<html>
<head>
<title>Jquery Document ready() Tutorial</title>
<style type="text/css">
ul li{color: green;}
</style>
<script src="jquery-1.8.3.js"></script>
<script>
$(function(){
$('ul li').css('color','blue');
});
</script>
</head>
<body>
<ul>
<li>Title 1</li>
<li>Title 2</li>
<li>Title 3</li>
</ul>
</body>
</html>
- See the style has been added to the list item – image taken from chrome developer’s tool
Run jQuery code, without making use of jquery document ready()
In order to avoid making use of the ready() event, you can just put our javaScript code prior to the ending
VimalTuts Code Junction 
