Cainiao JS (5) -- window. onload and $ (document). ready (), jswindow. onload
We continue to talk about JS. We often perform some operations after page loading, such as the display and hiding of some elements and some animation effects. We usually have two methods to accomplish this. One is the window. onload event, and the other is the ready () method of JQuery. So what are the differences between the two methods? Look down:
The onload event is triggered after all elements and content on the page are loaded. The ready () method is triggered after the DOM structure of the page is loaded. That is to say, the ready () method will be executed before the onload event.
For example:
Suppose there is a page showing the image library. This page may contain many large images, which can be hidden, displayed, or operated in other ways through jQuery. If we use the onload page setting interface, you must wait until each image is downloaded before you can use this page. What's worse, if a behavior is slightly added to elements with default behaviors (such as links), user interaction may lead to unexpected results. However, when we try to set $ (document). ready () {}, this interface will prepare the correct actions available earlier.
Use $ (document ). ready () {} is generally better than the onload event handler, but it must be clear that the support file may not be completed yet, therefore, attributes such as the image height and width are not necessarily valid at this time.
Onload events are generally written as follows:
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});
Or:
$(function(){//your code});
Next, let's look at two examples:
function first(){ alert("first");}function second(){ alert("second");}window.onload = second;window.onload = first;
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? Because onload is an event, it can only bind one value, and the latter will overwrite the previous one. ready () is a method, and the methods do not affect each other, so they will be executed sequentially.
OK. After the comparison, the differences between onload and ready () are obvious. I don't need to talk about it in any case!