Timing differences between $(document).ready() and window.onload()
Introduction
In JavaScript, window.onload event fires when a
document is completely downloaded to the browser. This means that every element
on the page is ready to be manipulated by JavaScript, which is a boon for
writing featured code without worrying about load order.
On the other hand, jQuery's $(document).ready() is
invoked when the DOM is completely ready for use. This also means that all
elements are accessible by our scripts, but does not mean that every associated
file has been downloaded. As soon as the HTML has been downloaded and parsed
into a DOM tree, the code can run.
Example
Think of a page that presents an image gallery; such a
page may have many large images on it, which we can hide, show, move, and
otherwise manipulate with jQuery. If we set up our interface using the onload
event, users will have to wait until each and every image is completely
downloaded before they can use those features. Even worse, if behaviors are not
yet attached to elements that have default behaviors (such as links), user
interactions could produce unintended outcomes.
So, when we use $(document).ready() for the setup, the
interface is ready to use earlier with the correct behavior.
Read next post for its real example.
Comments
Post a Comment