window.onload vs $(document).ready()
The ready
event occurs after the HTML document has been loaded, while the onload
event occurs later, when all content (e.g. images) also has been loaded.
The onload
event is a standard event in the DOM, while the ready
event is specific to jQuery. The purpose of the ready
event is that it should occur as early as possible after the document has loaded, so that code that adds functionality to the elements in the page doesn't have to wait for all content to load.
jQuery - What are differences between $(document).ready and $(window).load?
$(document).ready(function() {
// executes when HTML-Document is loaded and DOM is ready
console.log("document is ready");
});
$(window).load(function() {
// executes when complete page is fully loaded, including all frames, objects and images
console.log("window is loaded");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Jquery .ready() vs window.onload
Depends on what you want to do.
- jQuery ready will run your code when the HTML is all ready, but before images and other resources have finished. This is the earliest possible time that you can change the DOM with JavaScript, so it's widely used. (In modern browsers it's replaced by the native event
DOMContentLoaded
). window.onload
(theload
event) runs after everything has finished loading. Images, Flash, and some scripts, but usually not stylesheets. Use this for code that should run only when the page won't change any more.
Also, with window.onload
you can only attach one listener, but you can attach as many as you want with jQuery ready. To attach more than one event on window.onload
, use addEventListener
:
window.addEventListener('load', function () {
}, false);
window.onload vs document.ready jQuery
I had a same problem in handling Image height and width inside $(document)ready and I found some better referenses to solve it... I hope this may help some one
$(document).ready()
The document ready event fired when the HTML document is loaded and the DOM is ready, even if all the graphics haven’t loaded yet. If you want to hook up your events for certain elements before the window loads, then $(document).ready is the right place.
Code:
$(document).ready(function() {
// document is loaded and DOM is ready
alert("document is ready");
});
$(window).load()
The window load event fired a bit later, when the complete page is fully loaded, including all frames, objects and images. Therefore functions which concern images or other page contents should be placed in the load event for the window or the content tag itself.
Code:
$(window).load(function() {
// page is fully loaded, including all frames, objects and images
alert("window is loaded");
});
JS window.onload Usage Vs Document
Load Event on window:
The load event fires at the end of the document loading process. At
this point, all of the objects in the document are in the DOM, and all
the images, scripts, links and sub-frames have finished loading.
[source: developer.mozilla.org]
<script>
window.onload = function(){ init(); };
</script>
Load Event on HTML Elements:
The
load
event is fired when a resource and its dependent
resources have finished loading.
[source: developer.mozilla.org]
<!-- When the image is loaded completely -->
<img onload="image_loaded()" src="w3javascript.gif">
<!-- When the frame is loaded completely (including all resources) -->
<iframe onload="frame_loaded()" src="about.html">
<!-- When body loaded completely (including all resources, images and iframes) -->
<body onload="init()">
Many forums even some answers in this site may mislead you, but the load
event on body element is not only just equivalent to load
event on window, it is the exact same event. The following quote clarifies it.
For historical reasons, some attributes/properties on the
<body>
and
<frameset>
elements actually set event handlers on their parent Window
object. (The HTML specification names these: onblur, onerror, onfocus,
onload, onscroll.)
[source: developer.mozilla.org]
The DOMContentLoaded Event:
What developers should use is DOMContentLoaded
event on document. It fires when the html has loaded and parsed completely.
document.addEventListener("DOMContentLoaded", function(event) {
alert("Document is ready");
});
The DOMContentLoaded event is fired when the initial HTML document has
been completely loaded and parsed, without waiting for stylesheets,
images, and subframes to finish loading. A very different event load
should be used only to detect a fully-loaded page. It is an incredibly
popular mistake to use load where DOMContentLoaded would be much more
appropriate, so be cautious.
[source: developer.mozilla.org]
Perhaps this is the only answer regarding this topic that has proper References
Difference between onload() and $.ready?
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).
window.onload vs document.onload
When do they fire?
window.onload
- By default, it is fired when the entire page loads, including its content (images, CSS, scripts, etc.).
In some browsers it now takes over the role of document.onload
and fires when the DOM is ready as well.
document.onload
- It is called when the DOM is ready which can be prior to images and other external content is loaded.
How well are they supported?
window.onload
appears to be the most widely supported. In fact, some of the most modern browsers have in a sense replaced document.onload
with window.onload
.
Browser support issues are most likely the reason why many people are starting to use libraries such as jQuery to handle the checking for the document being ready, like so:
$(document).ready(function() { /* code here */ });
$(function() { /* code here */ });
For the purpose of history. window.onload
vs body.onload
:
A similar question was asked on codingforums a while
back regarding the usage ofwindow.onload
overbody.onload
. The
result seemed to be that you should usewindow.onload
because it is
good to separate your structure from the action.
Why does window.onload event occur before $(document).ready?
The problem is not with the order of the events. It with the jQuery wrapper around the native DOM events. If you try the native DOMContentLoaded
you will find that it always runs before window.onload
. But the jQuery event$(document).ready
will come some milliseconds after DOMContentLoaded
, which in some cases might be after window.onload
too, especially if the page doesn't have much to load like the code below. This is delay is due to jQuery implementation.
If you uncomment the iframe in the code though, it takes some time to load which causes the window.onload
to be delayed, so $(document).ready
will come first.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<h1>A Simple Site</h1>
<!-- <iframe src="http://stackoverflow.com"></iframe> -->
<script>
$(document).ready(function() {
console.log("jQuery ready");
})
document.addEventListener("DOMContentLoaded", function(event) {
console.log("DOM ready");
});
window.onload = function() {
console.log("DOM loaded");
}
</script>
</body>
</html>
Difference between $(window).load() and $(document).ready() functions
document.ready
is a jQuery event, it runs when the DOM is ready, e.g. all elements are there to be found/used, but not necessarily all content.window.onload
fires later (or at the same time in the worst/failing cases) when images and such are loaded, so if you're using image dimensions for example, you often want to use this instead.
Related Topics
Persist Variables Between Page Loads
How to Pad a Value With Leading Zeros
How to Read a Local Text File in the Browser
_Proto_ Vs. Prototype in JavaScript
What Is a Good Regular Expression to Match a Url
Explain the Encapsulated Anonymous Function Syntax
Xml Parsing of a Variable String in JavaScript
Detecting an "Invalid Date" Date Instance in JavaScript
How to Delay the .Keyup() Handler Until the User Stops Typing
How to Check That a Number Is Nan in JavaScript
How to Remove a Property from a JavaScript Object
Short Circuit Array.Foreach Like Calling Break
Wait Until All Jquery Ajax Requests Are Done
How to Get Jquery to Perform a Synchronous, Rather Than Asynchronous, Ajax Request
Can't Append ≪Script≫ Element
How to Get the Caret Column (Not Pixels) Position in a Textarea, in Characters, from the Start
How to Force Js to Do Math Instead of Putting Two Strings Together
Can Scrapy Be Used to Scrape Dynamic Content from Websites That Are Using Ajax