Monday, January 28, 2013

Difference between document.ready and window.onload or pageLoad

In Asp.Net Web applications, developers use the jquery’s $document.ready() and pageLoad() or window.onload events very frequently. In the first sight these events seems very similar in functioning. But $document.ready()  and pageLoad() methods are very differ in functioning.

In this post I am trying to expose the difference between $document.ready()  and pageLoad() .

 

$document.ready()-


$document.ready() method of jquery gets called as soon as DOM is ready (means browser has parsed the HTML and built the DOM tree) . It is cross browser compatible means it behaves same in all the browsers. We can have multiple $document.ready() methods on a web page and they will be called in coming sequence. 
<script type="text/javascript">
 $document.ready(function () {
   //Gets called as soon as DOM is ready
   // it may called before pageLoad() method.
   //code here
 });
</script>   

 

pageLoad()(window.onload)-


pageLoad() method gets called when images and all associated resources of the page have been fully loaded. Suppose your web page has large size images then until all the images are not fully loaded on the page, pageLoad() method will not called. pageLoad() method is not browser compatible. We can have only one pageLoad() method on a web page.
<script type="text/javascript">
   function pageLoad() {
     // gets called when page have been fully loaded
            //code here
   }
</script>

 

pageLoad() and $document.ready() methods in Partial Postback-


Since we know, in asp.net update panel gets partially postback to the server. Hence if you are using the pageLoad() and $document.ready() methods in your web page then you should be very careful to use these methods.
pageLoad() method is called each and every partial postback whereas $document.ready() is not called in every partial postback. $document.ready() is called only one time i.e. during first time of page loading.

Summary

In this article I try to expose $document.ready() and window.onload/pageLoad(). I hope after reading this article you will be able to understand the use of both these methods. 

Happy reading!!
kick it on DotNetKicks.com

No comments:

Post a Comment

If You Enjoyed This Post Please Take 5 Seconds To Share It.

^ Scroll to Top hgpromo