window.onload vs $(document).ready()
Solution 1
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.
Solution 2
window.onload
is the built-in JavaScript event, but as its implementation had subtle quirks across browsers (Firefox, Internet Explorer 6, Internet Explorer 8, and Opera), jQuery provides document.ready
, which abstracts those away, and fires as soon as the page's DOM is ready (doesn't wait for images, etc.).
$(document).ready
(note that it's not document.ready
, which is undefined) is a jQuery function, wrapping and providing consistency to the following events:
-
document.ondomcontentready
/document.ondomcontentloaded
- a newish event which fires when the document's DOM is loaded (which may be some time before the images, etc. are loaded); again, slightly different in Internet Explorer and in rest of the world - and
window.onload
(which is implemented even in old browsers), which fires when the entire page loads (images, styles, etc.)
Solution 3
$(document).ready()
is a jQuery event. JQuery’s $(document).ready()
method gets called as soon as the DOM is ready (which means that the browser has parsed the HTML and built the DOM tree). This allows you to run code as soon as the document is ready to be manipulated.
For example, if a browser supports the DOMContentLoaded event (as many non-IE browsers do), then it will fire on that event. (Note that the DOMContentLoaded event was only added to IE in IE9+.)
Two syntaxes can be used for this:
$( document ).ready(function() {
console.log( "ready!" );
});
Or the shorthand version:
$(function() {
console.log( "ready!" );
});
Main points for $(document).ready()
:
- It will not wait for the images to be loaded.
- Used to execute JavaScript when the DOM is completely loaded. Put event handlers here.
- Can be used multiple times.
- Replace
$
withjQuery
when you receive "$ is not defined." - Not used if you want to manipulate images. Use
$(window).load()
instead.
window.onload()
is a native JavaScript function. The window.onload()
event fires when all the content on your page has loaded, including the DOM (document object model), banner ads and images. Another difference between the two is that, while we can have more than one $(document).ready()
function, we can only have one onload
function.
Solution 4
A Windows load event fires when all the content on your page is fully loaded including the DOM (document object model) content and asynchronous JavaScript, frames and images. You can also use body onload=. Both are the same; window.onload = function(){}
and <body onload="func();">
are different ways of using the same event.
jQuery $document.ready
function event executes a bit earlier than window.onload
and is called once the DOM(Document object model) is loaded on your page. It will not wait for the images, frames to get fully load.
Taken from the following article:
how $document.ready()
is different from window.onload()
Solution 5
A little tip:
Always use the window.addEventListener
to add an event to window. Because that way you can execute the code in different event handlers .
Correct code:
window.addEventListener('load', function () {
alert('Hello!')
})
window.addEventListener('load', function () {
alert('Bye!')
})
Invalid code:
window.onload = function () {
alert('Hello!') // it will not work!!!
}
window.onload = function () {
alert('Bye!')
}
This is because onload is just property of the object, which is overwritten.
By analogy with addEventListener
, it is better to use $(document).ready()
rather than onload.
Comments
-
Vaibhav Jain over 2 years
What are the differences between JavaScript's
window.onload
and jQuery's$(document).ready()
method? -
Tim Down over 13 yearsThere's a slight misconception here: the
load
event ofwindow
is implemented reasonably consistently across browsers. The problem that jQuery and other libraries are trying to solve is the one you mentioned, which is that theload
event is not fired until all dependent resources such as images and stylesheets have loaded, which could be a long time after the DOM is completely loaded, rendered and ready for interaction. The event that fires in most browsers when the DOM is ready is calledDOMContentLoaded
, notDOMContentReady
. -
Piskvor left the building over 13 years@Tim Down: reasonably is the key word here; at least some object sniffing used to be necessary, even with
onload
(there are differences wrt FF/IE/Opera). As for theDOMContentLoaded
, you are entirely correct. Editing to clarify. -
Tim Down over 13 yearsWhat kind of object sniffing do you mean?
-
Piskvor left the building over 13 years@Tim Down: IIRC, Opera's
window.onload
didn't work correctly (as of 9.04), so you had to sniff for window.opera and hookdocument.onload
; also, there was (is?) a different way of registering for events in IE and in normal browsers (window.onload=function(){}
works everywhere, yes, but clobbers whatever was there previously). I may not recall this clearly, as jQuery'sdocument.ready
has freed me from this kind of drudgery, many years ago :) -
Tim Down over 13 yearsOK. Opera has had
window.onload
for ages (since version 7 maybe? Certainly prior to version 9). Not sure what your point about IE is: are you referring to what happens when bothwindow.onload
is assigned and<body>
has anonload
attribute? That does indeed vary between browsers, but that situation should simply be avoided. Agreed that a library does simplify this kind of thing, but in general,window.onload = function() { ... };
works well in all major browsers so long as there's noonload
attribute in the<body>
element. -
Piskvor left the building over 13 years@Tim Down: I know Opera had it, but the event trigger on it was slightly quirky (to trigger reliably,
document.onload
was usable). As far as the window.onload goes:window.onload = fn1;window.onload=fn2;
- only fn2 would get invoked onload. Some free webhosts insert their own code into documents, and sometimes this clobbered the in-page code. -
Monica over 11 yearsWhich version of IE? I know I should care about compatibility, but it's hard to with IE. Is it acceptable to use document.ready for just JavaScript?
-
James Drinkard over 11 yearsIE6, 7, and 8. See: stackoverflow.com/questions/13185689/…
-
Jorge Orpinel Pérez over 10 yearsThere's also document.onload (see stackoverflow.com/questions/588040/…)
-
A. Sallai about 10 yearsIsn't writing "document.ready" incorrect? the document object doesn't have a ready method, the jQuery object does that is returned from the $(document) call. Please edit this answer if I'm right because this is very confusing.
-
A. Wolff about 10 years@baptx not same result, document ready handler will be fired even setted after DOM is effectively ready, using a promise.
DOMContentLoaded
won't. So document jquery ready handler can really be useful when setted in external script load asynchronously -
ToolmakerSteve almost 10 yearsFYI, The link @baptx gave, itself links to a js function based on
DOMContentLoaded
(when it exists) orreadystatechanged
(for IE): github.com/dperini/ContentLoaded/blob/master/src/… so presumably that is roughly what it takes to implement jQuery'sready
. -
ToolmakerSteve almost 10 yearsMinor point: The discussion of IE is poorly worded. It isn't that IE (8 and before) "can't safely fire" until the document's readyState reaches complete, it is that IE lacked a DOMContentLoaded event. Not a matter of "safety", but a missing feature in IE, added in IE 9.
-
Rituraj ratan over 9 yearstech-blog.maddyzone.com/javascript/… hope this will helpful
-
James Drinkard about 9 yearsYou are correct, so I edited the answer to reflect your comment and thanks!
-
Dariux almost 9 yearsYou say "It will not wait for the images to get loaded." what about other files, js most importantly? Often before calling function from another file - I need to know if it is loaded.
-
James Drinkard almost 9 yearsThis is another topic altogether, but if I understand what you are asking, it's based on how you structure your page, including what order you place the js files. Here is a link that goes into more detail: ablogaboutcode.com/2011/06/14/… HTH, James
-
Haoyu Chen over 8 yearsI think this is the best answer!
-
Usman over 8 yearsWhy will someone want to use $(document).ready() multiple times?
-
Nabeel Khan over 8 yearscan you please explain $(document).load(handler) behaves same as binding to the load-event. Unlike $.fn.ready, it will not call through immediately ?
-
abstraktor over 8 yearsI think you got confused by
$.fn.load
that doesn't behave as event binder anymore. In fact, it's obsoleted since jquery 1.8. I updated it accordingly -
Scott Marcus about 8 yearsThere is no such event as
onload
.onload
is the name of an object property that stores a function to be invoked when theload
event is triggered. -
Kevin B almost 8 yearsI might agree, if it weren't copied word-for-word.
-
user369142 over 7 yearsFor images this solved my problem exactly, I was getting incorrect height and width values from the document.ready when doing a hard refresh which makes perfect sense with the explanation in the original post. Thanks!
-
Ganpat Kakar over 5 yearsif i don't have external css or js or any images to load in a html file still my winodw.onload triggers later then document.ready event why is that so, but from the behavior i can see even though it register both the events at the same time but it will trigger the document.ready event first. I understood the reason that why document.ready loads fist but even though window is the parent of document object model still it will trigger later, why
-
Guffa over 5 years@GanpatKakar: One event simply has to be triggered before the other, even if the time difference is nearly zero. It's more reliable to trigger the events in the same order even if there are no other resources to load than the document itself.
-
vik over 5 years"window.onload is a function" is incorrect as @Илья-Зеленько demonstrates it is a property and not a function. Details: developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/… whereas .ready() is a function and expects a handler.
-
Admin over 5 yearsThis doesn't answer the question asked.