[英]will onLoad always be fired after DOM ready?
我想在DOM准备就绪时禁用我的插件对DOM做的一些特定“功能”。
如果我将我的代码放在onload
回调中,它是否会在ready
回调之后执行?
我希望在100%中确保即使没有任何图像只有少数准备将在onload之前执行。
虽然我认为@ jAndy的答案是正确的,但你可以通过在ready()
调用中将代码放在onload
来为自己提供一些额外的保证。
只需确保您的主要ready()
调用是第一位的。
$(document).ready(function() {
// Your normal ready handler
});
$(window).load(function() {
// Placing code in another .ready() call in here will add it to the
// end of internal Array of ready handlers if any are pending
$(document).ready(function() {
// my onload code
});
});
因此,如果在onload
触发时ready()
已经触发,则onload
代码仍将运行。 (一旦DOM准备就绪,就会设置内部标志,因此将立即调用将来的.ready()
调用。)
如果.ready()
在onload
发生时以某种方式没有被触发,这意味着你的原始ready()
代码首先在内部Array中,并且新的.ready()
代码将被添加到Array的末尾。
编辑:
查看在 DOM准备就绪时触发的主要jQuery.ready
处理程序的源代码 (反过来,触发用户的.ready()
处理程序的列表) ,看起来似乎有一个IE错误处理程序触发了早一点。
为了解决这个错误,jQuery使异步调用处理程序直到它实际上可以看到document.body
。
ready: 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.fireWith(document, [jQuery]);
// Trigger any bound ready events
if (jQuery.fn.trigger) {
jQuery(document).trigger("ready").off("ready");
}
}
},
看起来由于处理程序的这种异步循环,IE至少可能倾向于在.ready()
处理程序之前调用window.onload
处理程序。
如上所述,添加到onload
的.ready()
处理程序列表应该可以解决这个问题。
是。
onload
将会触发, DOMContentLoaded
就会触发。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.