JavaScript

What is the difference between $(document).ready() and window.onload?

April 27, 2022

What is the difference between $(document).ready() and window.onload?

In this article we will learn the difference between $(document).ready() and window.onload – what these two statements can do in each use case

difference between $(document).ready() and window.onload thumb

What’s up programmer! 

Let’s get to know both instructions in depth!

Understand $(document).ready

The $(document).ready statement was created in jQuery, and it is for the JavaScript code to be executed only when the HTML is loaded

This prevents the code we create from failing because some elements are not yet rendered in the HTML.

We guarantee that the same will only be valid after the entire tree of HTML elements are fully inserted in the page.

No matter where the JavaScript/jQuery code is positioned

Understand window.onload

The window.onload instruction is native to JavaScript, we can use it with jQuery, but the opposite does not happen, ready does not work with pure JS

And when using this event, JavaScript understands that the code housed in it should start taking effect only when all the elements on the page load.

That is, in addition to the HTML tags, the images must also be ready and visible.

So the ready statement is more performant, because the code can already be executed before the code that is inserted in window.onload

But if you’re not using jQuery, the only way out of your page load problem is onload, keep that in mind

Conclusion

In this article we learned the difference between $(document).ready() and window.onload

The ready statement was developed for jQuery, not available in JS Vanilla

Onload is native to JavaScript.

The code inside ready is executed as soon as all HTML elements are loaded, while onload all page elements need to be loaded for the JS code to run

Do you want to learn more about JS and web development? Click here!

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x