Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

聊一聊前端八股 window.onload vs $(document).ready() 有啥区别 #26

Open
yuqingc opened this issue Nov 17, 2020 · 0 comments
Open
Labels
javascript about JavaScript

Comments

@yuqingc
Copy link
Member

yuqingc commented Nov 17, 2020

ready 事件在 HTML 文档加载后发生,而 onload 事件在稍后加载所有内容(例如图像)时发生。

onload 事件是 DOM 中的标准事件,而 ready 事件特定于 jQuery。 ready 事件的目的是,它应该在文档加载后尽早发生,从而使向页面中的元素添加功能的代码不必等待所有内容加载。

来自 StackOverflow

The ready event occurs after the HTML document has been loaded, while the onload event occurs later, when all content (e.g. images) also has been loaded.

The onload event is a standard event in the DOM, while the ready event is specific to jQuery. The purpose of the ready event is that it should occur as early as possible after the document has loaded, so that code that adds functionality to the elements in the page doesn't have to wait for all content to load.

那就一次性弄明白

Window 的 load 事件

  • load 事件发生在所有内容加载完成之后

Document 的 DOMContentLoaded 事件

  • load 不同,该事件发生在文档加载完成之后

Document.readyStatereadystatechange 事件

Document.readyState

  • loading: 加载中

  • interactive: 此时 readyState 为 'interactive',表明 document 已经 load 并解析完成,触发 readystatechange,然后触发 DOMContentLoaded (在大多数浏览器上的表现如此)

  • complete: 所有资源加载完成。load 事件即将触发

jQuery 的 ready 事件和 DOMContentLoaded 的比较

查阅了 jQuery 的文档之后,做出以下总结

  • 事件发生在 DOM 安全的加载完成之后,触发之后,可以安全的操作 DOM 了

  • 如果 DOM 加载完毕,并且在代码调用 .ready(handler) 之前触发了 DOMContentLoaded 事件,那么 ready 的回调函数仍然会执行,但是浏览器原生 DOMContentLoaded 的监听函数不会执行

单纯比较 jQuery 的事件和原生事件意义不大,因为 jQuery 的事件依赖原生事件

此话题终结!

@yuqingc yuqingc added the javascript about JavaScript label Nov 17, 2020
@yuqingc yuqingc changed the title 聊一聊前端八股 window.onload vs $(document).ready() 聊一聊前端八股 window.onload vs $(document).ready() 有啥区别 Nov 20, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
javascript about JavaScript
Projects
None yet
Development

No branches or pull requests

1 participant