Difference between document.ready() vs window.load()
A common question in any interview (jQuery) for beginners,
"How do I perform various actions as soon as the page loads on the client side in JavaScript?", document.ready()
or window.load()
.
In this article, I will explain the major differences between $(document).ready()
and window.load()
.
$(document).ready()
jQuery’s $(document).ready()
method 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 behave equally on all browsers. If your web page has large images,
it will not wait for loading of images completely.
We can have multiple $(document).ready()
methods on a web page that will be called in coming sequence.
DOM: The Document Object Model (DOM) is a cross-platform and language-independent convention for representing and interacting with objects in HTML, XHTML and XML documents.
$(document).ready(function() // executes when HTML-Document is loaded and DOM is ready alert("(document).ready was called - document is ready!"); });
Note: If you want to use the Height, Width properties of an image for example, then $(document).ready()
is a deal braker!!
window.load() (Built-in JavaScript)
The window.load however will wait for the page to be fully loaded, this includes inner frames, images etc.
$(window).load(function() { // executes when complete page is fully loaded, including all frames, objects and images alert("(window).load was called - window is loaded!"); });
window.load()
is a built-in JavaScript method, it is known to have some quirks in old browsers (IE6, IE8, old FF and Opera versions) but will generally work in all of them.
window.load()
can be used in the body's onload event like this (but I would strongly suggest you avoid mixing code like this in the HTML, as it is a source for confusion later on):
Breaking change: .load(), .unload(), and .error() removed(jQuery 3.0)
These methods are shortcuts for event operations, but had several API limitations. The event .load()
method conflicted with the ajax.load()
method. The .error()
method could not be used with window.onerror because of
the way the DOM method is defined. If you need to attach events by these names, use the
.on()
method, e.g. change $("img").load(fn)
to $("img").on("load", fn)
.
These are all equivalent:
$(function(){ }); jQuery(document).ready(function(){ }); $(document).ready(function(){ }); $(document).on('ready', function(){ });
Summary
To summarise, $(document).ready()
is called as soon as DOM is ready where as window.load()
wait for the page to be fully loaded.
Hope you picked up a thing or two.
Cheers!