how $document.ready() is different from window.onload()

we often use window.onload() in javascript and $document.ready() in jquery and assume that both are same just jquery library wrap up javascript window.onload() and introduce $document.ready() but no there is much difference between them below is the explanation -

window.onload() (<body onload="func();" >) -

The load event fires when all the content on your page fully loaded including the DOM (document object model) content, asynchronous javascript, frames and images, you can also use body onload= both are same just window.onload = func(){} and <body onload="func();"> are different ways of using the same event.


$(window).load(function () {
         alert("window load complete");
});

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

$document.ready() -

Jquery $document.ready function event executes a bit earlier than window.onload and called once the DOM(Document object model) is loaded on your page. DOM means all the html tags/script I.e.(anchor tag, table, div tag, paragraph tag etc..). It will not wait for the images, frames to get fully load. It means that it is the earliest stage in page load process.


$(document).ready(function () {
          alert("document is ready.");

});



The main difference is that $document.ready() event gets called as soon as your DOM is loaded. It does not wait for the contents to get loaded fully. For example, there are very heavy images on any web page and takes time to load. If you have used window.onload then it will wait until all your images are loaded fully, hence it slows down the execution. On the other side, $document.ready() does not wait for elements to get loaded.

$document.ready() , window.onload() inside update panel (partial postback) in asp.net

Since we know, in asp.net update panel gets partially postback (use xmlhttprequest object) to the server. Hence if you are using the $document.ready() or window.onload methods in your web page then you should be very careful to use these methods.

$document.ready() is not called in every partial postback. $document.ready() is called only one time i.e. during first time of page loading. if you want to get call back of every partial postback then you have to use pageLoad() method which is the part of scriptmanager generated script means if you want to use pageLoad() method then you need to use asp.net scriptmanager in the page.




Recent Article