Both document.ready and window.onload event is used to perform the action when webpage is loaded. What’s the difference between these two events.
The difference between document.ready and window.onload is most asked javascript interview question for both fresher and experienced web developers.
Document Ready event
Let’s write a short snippet.
1 2 3 4 |
$(document).ready(function(){ // code to be executed }); |
Jquery document.ready event is fire as soon as DOM is ready. In simple words it fires when browser has parsed the HTML. So the above code snippet invoked when DOM is ready.
DOM Ready?
DOM ready means that all the HTML has been received and parsed by the browser into the DOM tree which can now be manipulated.
It occurs before the page has been fully rendered (as external resources may have not yet fully downloaded – including images, CSS, JavaScript and any other linked resources).
So in case of document.ready event if you are setting the height and width of an image, chances it might not give you the correct result.
Window Onload Event
Let’s check window.onload event.
1 2 3 4 5 6 7 |
window.onload = function() { //Fire when page is loaded completely. alert('onload'); } |
Window.onload event fires when the webpage is loaded completely. This event is triggered when all external resources (such as images,videos,iframes etc) is fully loaded.
1 2 3 4 5 6 7 |
function my_func(){ // Function body } window.onload= my_func(); |
Difference between document.ready and window.onload
1. The $(document).ready event trigger when DOM is ready (means browser has parsed the HTML and built the DOM tree). In case of document.ready method it is not necessary that all the contents (videos,images etc.) of a webpage is available.
As compared to $(document).ready(), the window.onload event is fired when all the element of a page is loaded completely (DOM as well as all it’s content such as images,js,css etc).
2. The window.onload is a standard event in the DOM as compared to document.ready which is specific to jquery.
3. You can write more than one $(document).ready(handler) function in a web page but only one window.onload function. In case of multiple document.ready event, browser will invoke them in the order they are declared in page.
In case of multiple window.onload event, the last onload will override any previous onloads.
Conclusion
I hope you will get the fair idea of document.ready and window.onload event. If i miss any point or you want to add anything, Please let us know by your comments.