Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery NewBie Questions: What's the deal with $(document).(ready)?

I am newbie to jQuery, just trying to learn it since last couple of days. In my office, there are few experience JavaScript Developer and they work mainly with jQuery for all their needs and whenever I got and talk to them to get some better understanding of how jQuery works and first they say is that on $(document).(ready) you do this and on $(document).(ready) you do that.

So my main question is What is the $(document).(ready) and how does it really works?

Any inputs would be highly appreciated.

Update: In the accepted answers comment there is mention on When DOM is ready, so what does that really means ?

like image 641
Rachel Avatar asked Apr 14 '10 15:04

Rachel


2 Answers

$(document).ready() fires once the DOM is completely loaded and ready for manipulation. This prevents your code from firing before the objects that it'll act against exist. $(document).ready() is the most verbose version of it, and can be replaced up with any of these statements...

$(document).ready(handler)
$().ready(handler) (this is not recommended)
$(handler)
$(document).bind("ready", handler)

See here for the documentation.

like image 143
Scott Ivey Avatar answered Oct 09 '22 23:10

Scott Ivey


I think it is best described in the tutorial:

Launching Code on Document Ready

The first thing that most Javascript programmers end up doing is adding some code to their program, similar to this:

window.onload = function(){ alert("welcome"); }

Inside of which is the code that you want to run right when the page is loaded. Problematically, however, the Javascript code isn't run until all images are finished downloading (this includes banner ads). The reason for using window.onload in the first place is that the HTML 'document' isn't finished loading yet, when you first try to run your code.

To circumvent both problems, jQuery has a simple statement that checks the document and waits until it's ready to be manipulated, known as the ready event:

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

Or in short, it guarantees that every element of the document is loaded so that you can access it, but it does not wait until the images are loaded.

like image 31
Felix Kling Avatar answered Oct 09 '22 23:10

Felix Kling