Sunday, October 3, 2010

Difference between onload and document.ready in JQuery

What is the difference between using $(document).ready function and window.onload() function ?
Ans: The onload handler for the window instance is used for executing statements after the entire page is fully loaded. Below is an example of syntax of window.onload function
window.onload = function() {
$("table tr:nth-child(even)").addClass("even");
Here the browser executes the onload code after the DOM tree is created and after all images and other external resources are fully loaded and after  the page is displayed in the browser window. As a result, visitors can experience a delay between the time that they first see the page and the time that the onload script is executed.
The $(document).ready function waits only until the document structure is fully parsed and the browser has converted the html into its DOM tree form before executing the script to apply the rich behaviors . that is it triggers the execution of code once the DOM tree, but not external image resources, has loaded. An example of defining such code is as below:
$(document).ready(function() {
$("table tr:nth-child(even)").addClass("test");

Here First, we wrap the document instance with the jQuery() function, and then we
apply the ready() method, passing a function to be executed when the document
is ready to be manipulated.

No comments:

Post a Comment