gpt4 book ai didi

jquery - $(document).ready() - 它是如何执行的?

转载 作者:行者123 更新时间:2023-12-01 01:09:40 25 4
gpt4 key购买 nike

$(document).ready() - 它是如何执行的?光标是否会在那段行中等待以在 DOM 创建后执行代码,或者此方法将在浏览器创建 DOM 后像事件处理程序一样执行?

如果图像未下载,但执行 $(document).ready() 来读取该图像的 src 属性并分配给其他局部变量,该怎么办DOM 构建之后?

最佳答案

它是一个事件处理程序,并且它不会等待所有内容下载。它只会等到 DOM 构建完成并准备好进行转换。来自 docs :

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.

实际上,其背后的代码相当简单。它只是等待 document.body 可访问(不为空):

function (wait) {
// Either a released hold or an DOMready/load event and not yet ready
if ((wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady)) {
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if (!document.body) {
return setTimeout(jQuery.ready, 1);
}

// Remember that the DOM is ready
jQuery.isReady = true;

// If a normal DOM Ready event fired, decrement, and wait if need be
if (wait !== true && --jQuery.readyWait > 0) {
return;
}

// If there are functions bound, to execute
readyList.resolveWith(document, [jQuery]);

// Trigger any bound ready events
if (jQuery.fn.trigger) {
jQuery(document).trigger("ready").unbind("ready");
}
}
}

来自http://james.padolsey.com/jquery/#v=1.6.2&fn=jQuery.ready

关于jquery - $(document).ready() - 它是如何执行的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9828966/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com