Pages

Sunday, 10 June 2012

Anatomy of document.ready function in jQuery

All jQuery methods come inside a document.ready() function. This is to prevent any jQuery code from running before the document is finished loading (is ready).

Here are some examples of actions that can fail if functions are run before the document is fully loaded:

1. Trying to hide an element that doesn't exist
2. Trying to get the size of an image that is not loaded

document.ready syntax:

<div id="divTest1"></div>
<script type="text/javascript">
function DocumentReady()
{
        $("#divTest1").text("Hello, world!");   
}

$(document).ready(DocumentReady);
</script>
<div id="divTest2"></div>
<script type="text/javascript">
$(document).ready(function()
{
        $("#divTest2").text("Hello, world!");   
});
</script>

But of course, this syntax 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.

Difference between body onload() function used in javascript and document.ready() function used in jQuery

Document.ready() function is different from body onload() function because of 2 reasons:

1. We can have more than one document.ready() function in a page where we can have only one onload function.

2. Document.ready() function is called as soon as DOM is loaded whereas body.onload() function is called when everything gets loaded on the page that includes DOM, images and all associated resources of the page.

No comments:

Post a Comment