Monday, March 20, 2017

Difference between document.ready and window onload

Today we are going to look at the difference between document.ready and window.onload events.
In JavaScript we use window.onload() whereas in JQuery we are using $(document).ready() and normally developer think these both are same but it’s not true because there are many differences between them. Basically JQuery wrap up the window.onload() from JavaScript and give the world $(document).ready() but still both are different.
Let's have a look with example:

Window.onload():
This method called up when all data/content on a page is fully loaded here all content means DOM, images, async scripts etc all we have on a page. onload method must wait for images and other frames to load and after that this event is fired.

$(window).load(function () {
             alert("all content is loaded");
    });


By adding these lines to any page, it will show alert when page is fully loaded.There is another way to call this event is:

<body onload="func_call();" >


we can add this to the body tag of page and it will work same like $(window).onload.

$(document).ready():
JQuery execute earlier than window.onload. document.ready event is fired when all DOM is loaded on the page. DOM (document Object Model) include all html tag and scripts it does not include the images and other frames. DOM load is early stage of a page to load that’s why this event starts earlier than window.onload(). so when DOM is ready document.ready() event will start execution.

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


Another way which work same like document.ready or we can say shorthand for document.ready is:

$(function() {
        alert("DOM is ready." );
    });


Notes:
  1. Window.onload is a JavaScript event and document.ready is specific event from JQuery.
  2. If you have to perform some manipulation on images then its preferred to use window.load but if your operations are only related to DOM then use document.ready.
  3. On a single page we cannot use window.load event more than one whereas document.ready is allowed to use more than once. we can have multiple document.ready but window.load will be single on a page.

Comment and suggestion are always welcome.

No comments:

Post a Comment