We continue to say JS, we often do some things after the page loading, such as the display of some elements and hidden, some animation effect. We usually have two ways to do this, one is the Window.onload event and the other is the ready () method of jquery. So what is the difference between these two methods? Look down:
The onload event is triggered after all the elements in the page and when the content is fully loaded; The Ready () method is triggered after the page's DOM structure has been loaded. This means that the ready () method executes before the OnLoad event.
To give an example:
Suppose you have a page that behaves as a gallery, which may contain many large images that we can hide, display, or otherwise manipulate through jquery. If we set the interface through the onload page, then users must wait until each image is downloaded before they can use the page. Worse, if the behavior is slightly added to the elements that have the default behavior (such as links), then the user's interaction can lead to unexpected results. However, when we try to set the $ (document). Ready () {}, the interface is prepared for the correct behavior to be available earlier.
Use $ (document). Ready () {} is generally superior to the trial onload event handler, but it must be clear that attributes such as the height and width of the image are not necessarily valid at this time because the supporting files may not be home-finished.
The onload event is usually written in the following form:
function MyFunction () {//your code};window.onload = MyFunction;
Or:
Window.onload = function () {//your code};
The Ready () method is usually as follows:
$ (document). Ready (function () {//your code});
Or:
$ (). Ready (function () {//your code});
Again or:
$ (function () {//your code});
Let's take a look at two more examples:
function First () { alert ("First");} function second () {
This code will pop up "first".
function First () {alert ("First");} function second () {alert ("Second");} $ (document). Ready (function () {first ();}); $ (document). Ready (function () {second ();});
The above code will pop up "first" and "second" respectively.
Why is that? Because OnLoad is an event, it can only bind a value, and the following will overwrite the previous one, while Ready () is a method that does not affect each other, so it is executed sequentially.
OK, do the above comparison, the difference between OnLoad and ready () is very obvious, under what circumstances with no one I said more!
Beginners Learn js (v)--window.onload and $ (document). Ready ()