This week's book giveaway is in the OCPJP forum. We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line! See this thread for details.
Typically, when you want to perform actions when a page is loaded, you define an onload handler for the page. This is typically done by using the onload attribute of the <body> tag, or by assigning a function to window.onload.
The problem when using onload to initialize a page, is that it executes after all page elements, including external resources, have loaded. This creates a delay in which your page is persented to the user when it may not be quite ready for the user to interact with (because the onload handler hasn't fired yet).
jQuery solves this problem by introducing the document ready handler.
This handler is executed when the DOM has been created, but before the page is presented to the user. This guarantees that you can set up the page prior to the user being able to interact with it.
Without jQuery, setting this up is tricky to do in a cross-browser fashion, but jQuery makes it easy.
There's a formal syntax for defining a ready handler, but the easy short-hand method is to simple pass a function literal to the $() function. For example in a <script> block, you could write:
Moreover, you can conveniently define as many such blocks as you like (as opposed to a single onclick handler) and they will all execute when the DOM is ready. [ January 15, 2008: Message edited by: Bear Bibeault ]