window.onload与$(document).ready()


Many people don't know the usage and function of window.onload and $(document).ready() in JavaScript. Let's talk about their usage.

First talk about the usage of window.onload.

window.onload must wait for all elements in the web page to be loaded before it can be executed (including images or files).

Here is an example:

window.onload=function(){

alert("First output content")

};

window.onload=function(){

alert("Second output content")

};

 

  The result of running the code is the output: the second output content proves that window.onload cannot write multiple definitions at the same time, which is equivalent to repeating the definition, and only outputs the last definition. Pay attention to the usage when writing the code.

 

 

$(document).ready() is different. He can write multiple runtimes at the same time without waiting for all elements related to the DOM to be loaded. As long as the DOM structure is drawn, it can be executed. It is mostly used for pictures or files. The preparation of web pages, and the $(document).ready() method is the most important function in the event module, which can greatly improve the speed of web applications.

Here is an example of the code:

 

$(document).ready(function(){
alert("First output");
});
$(document).ready(function(){
alert("Second output");
});

 

 

 The output result is the first output, click OK to output the second output; he can write multiple at the same time, and there is also a simple way of writing

1:

$(function(){
alert("First output");
});
$(function(){
alert("Second output");
});

 2:

$().ready(function(){
// Write code
})

 

 The above three methods can be selected according to your own preferences.

 

 

Reprinted below

需要注意一点,由于在 $(document).ready() 方法内注册的事件,只要 DOM 就绪就会被执行,因此可能此时元素的关联文件未下载完。例如与图片有关的 html 下载完毕,并且已经解析为 DOM 树了,但很有可能图片还没有加载完毕,所以例如图片的高度和宽度这样的属性此时不一定有效。

此时我们可以用$(window).load(function(){....})。他可以弥补不足 也可以是代码更加清晰整洁

 

 

代码如下:

 $(window).load(function() {
           //编写代码
  });
 $(window).load(function() {
        //编写代码
 });

 

 

Load() 方法会在元素的 onload 事件中绑定一个处理函数。如果处理函数绑定给 window 对象,则会在所有内容 ( 包括窗口、框架、对象和图像等 ) 加载完毕后触发,如果处理函数绑定在元素上,则会在元素的内容加载完毕后触发。 这正是用$(window).load(function(){....})的一个原因。可以根据自己的需要进行选择。

 

 

 






 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326173208&siteId=291194637