The ready event

As mentioned in the previous chapter, it's good practice to wait for the document to be fully loaded and ready, before working with it. This also allows you to have your JavaScript code before the body of your document, in the head section, either directly or through a link to an external JavaScript file. You may do just that by placing your code inside the document ready event. We will use the same example as in the "Hello, world!" chapter, but this time the code is inside the ready event:
<div id="divTest1"></div>
<script type="text/javascript">
function DocumentReady()
{
	$("#divTest1").text("Hello, world!");	
}

$(document).ready(DocumentReady);
</script>
What we do here is that we create a function, called DocumentReady, which should be fired as soon as the document is ready for DOM manipulation. In the last line, we use the ready() method to assign our function to the ready event, to tell jQuery that as soon as the document is ready, we want it to call our function.

However, we can shorten this a bit by using an anonymous function of JavaScript instead. This basically just means that instead of declaring the function and giving it a name, we simply create it and then immediately passes the reference to the ready() function. If you're new to JavaScript, then this might seem overly complicated, but as you get used to it, you might appreciate the fewer keystrokes and the less space needed to accomplish the same:
<div id="divTest2"></div>
<script type="text/javascript">
$(document).ready(function()
{
	$("#divTest2").text("Hello, world!");	
});
</script>
But of course, this wasn't even short enough for the jQuery team, so they decided to create a version (overload) of the jQuery constructor which takes a ready function as a parameter, to make it even shorter:
<div id="divTest3"></div>
<script type="text/javascript">
$(function()
{
	$("#divTest3").text("Hello, world!");	
});
</script>
In the last example, our anonymous function is passed directly to the jQuery constructor, which assigns it to the ready event. As you will see when you test the code, the event is fired as soon as the page is loaded, most of the time so fast that you won't even realize it.

As already described, wrapping your code in the ready event function is best practice for working with jQuery in your document, and therefore you will see this tutorial using the approach in most of the examples, unless skipped to keep example sizes down.
<PreviousNext>
^ Back to Top