Difference between onload() and $.ready?
JavascriptJqueryOnloadJavascript Problem Overview
Can you list the difference between onload()
and $(document).ready(function(){..})
functions in the using jQuery?
Javascript Solutions
Solution 1 - Javascript
the load
event (a.k.a "onload") on the window and/or body element will fire once all the content of the page has been loaded -- this includes all images, scripts, etc... everything.
In contrast, jquery's $(document).ready(...)
function will use a browser-specific mechanism to ensure that your handler is called as soon as possible after the HTML/XML dom is loaded and accessible. This is the earliest point in the page load process where you can safely run script that intends to access elements in the page's html dom. This point arrives earlier (often much earlier) than the final load
event, because of the additional time required to load secondary resources (like images, and such).
Solution 2 - Javascript
The main differences between the two are:
- Body.Onload() event will be called only after the DOM and associated resources like images got loaded, but jQuery's document.ready() event will be called once the DOM is loaded i.e., it wont wait for the resources like images to get loaded. Hence, the functions in jQuery's ready event will get executed once the HTML structure is loaded without waiting for the resources.
- We can have multiple document.ready() in a page but Body.Onload() event cannot.
Solution 3 - Javascript
Document.ready() function triggers as soon as HTML DOM loaded. But the onload() function will trigger after HTML DOM, all the body content like images loaded.
Solution 4 - Javascript
body.onload() cares about both HTML structure and assoicated resources where as document.ready() cares only about the HTML structure.
Solution 5 - Javascript
Onload take care about DOM and resources: it checks if images are loaded, script are ready to run and much more.
$.ready simply check if we have read the full DOM of the page.
Please check out this link for more explain and example: http://dailygit.com/difference-between-document-ready-and-window-load-in-jquery/
Solution 6 - Javascript
> onload() fires when all the content (everything) on the targeted eleement is fully loaded like CSS, images etc. > > $.ready indicates that code in it need to be executed once the targeted elements content loaded and ready to be manipulated by script. It won't wait for the images to load for executing the jQuery script. >
.
> Ex(body onload):
<body onload="loadBody()">
<script>
function myFunction() {
alert("Page is loaded");
}
</script>
</body
> Ex(onload on an element):
<img src="w3html.gif" onload="loadImg()" width="100" height="132">
<script>
function loadImg() {
alert("Image is loaded");
}
</script>
> Ex3 ($.ready):
<script type = "text/javascript">
$(document).ready(function() {
alert("$(document).ready fired");
});
</script>