从官网文档,看window.onload,document.onDOMContentLoaded和jQuery的$(document).ready有什么区别?

onload和DOMContentLoaded

根据MDN的定义,就一句话:
onload是整个页面各种资源(如图片样式等)全部加载完;而DOMContentLoaded在基本的HTML文档被加载解析完,就执行,不等待 样式图片等其他资源。

The onload property of the GlobalEventHandlers mixin is an EventHandler that processes load events on a Window, XMLHttpRequest, element, etc. [1]
A different event, load, should be used only to detect a fully-loaded page. It is a common mistake to use load where DOMContentLoaded would be more appropriate. [2]
The DOMContentLoaded event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. [2]

jQuery的$(document).ready,以及与DOMContentLoaded区别

根据官方文档[3]
在页面中所有DOM (Document Object Model)被加载至安全状态后(具体啥叫”安全“不知道),就按序执行handler。jQ3.0甚至在有异常时,也会继续执行handler。

官方文档[3] The .ready() method offers a way to run JavaScript code as soon as the page's Document Object Model (DOM) becomes safe to manipulate. This will often be a good time to perform tasks that are needed before the user views or interacts with the page, for example to add event handlers and initialize plugins. When multiple functions are added via successive calls to this method, they run when the DOM is ready in the order in which they are added. As of jQuery 3.0, jQuery ensures that an exception occuring in one handler does not prevent subsequently added handlers from executing.

可见,与DOMContentLoaded类似,那么它
$(document).ready与DOMContentLoaded区别:
根据官方文档[3]
在dom准备完后,若 浏览器 先 触发了DOMContentLoaded,之后才去触发 .ready( handler ),此时, .ready()的handler还是会被执行的。
相反,在相关的事件被出发后,DOMContentLoaded监听器 就不会被触发执行了。

官方文档[3] Most browsers provide similar functionality in the form of a DOMContentLoaded event. However, jQuery's .ready() method differs in an important and useful way: If the DOM becomes ready and the browser fires DOMContentLoaded before the code calls .ready( handler ), the function handler will still be executed. In contrast, a DOMContentLoaded event listener added after the event fires is never executed.

另外推荐一篇关于本题的文章
https://www.jianshu.com/p/28a36a8ad95c
其中,该文指出了(document).ready()可以同时编写多个,并且可以得到执行

引用

[1] https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload
[2] https://developer.mozilla.org/en-US/docs/Web/API/Document/DOMContentLoaded_event
[3] https://api.jquery.com/ready/

你可能感兴趣的:(从官网文档,看window.onload,document.onDOMContentLoaded和jQuery的$(document).ready有什么区别?)