javascript - $(window).load 和 $(document).ready 有什么区别?

标签 javascript jquery document-ready

最近我的 JavaScript CODE 遇到了问题,我从 $(document).ready() 中取出一部分代码并将其放入 $(window) .load() 解决了这个问题。

现在我明白了 window.load 是在 document.ready 之后触发的,但是为什么它在 document.ready 之后还没有准备好,那是在 window.load() 之后?

最佳答案

load 在所有资源(包括图像)完成加载后调用。 ready 在 DOM 准备好进行交互时触发。

来自 MDC, window.onload :

The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images and sub-frames have finished loading.

来自 jQuery API 文档, .ready( handler ) :

While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code. When using scripts that rely on the value of CSS style properties, it's important to reference external stylesheets or embed style elements before referencing the scripts.

关于javascript - $(window).load 和 $(document).ready 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5182016/

相关文章:

javascript - 是否可以在图像开始加载之前运行 javascript?

javascript - 使用 mootools 多次替换元素名称

javascript - 打开对话框后如何返回主视图?

javascript - 为什么jQuery或诸如getElementById之类的DOM方法找不到元素?

javascript - CSS li 没有排队。可能是周期问题

jquery - 错误消息: Unable to get value of the property 'replace' : object is null or undefined in IE9

php - 如何保存 portlet 位置

javascript - 调用外部脚本和 .load jquery 冲突

JavaScript 背景图像被 $(document).ready 破坏

javascript - 单击时隐藏/显示元素并更改 CSS