jQuery如何“准备好文档"?功能正常吗? [英] How does jQuery's "document ready" function work?
问题描述
jQuery如何检查文档是否已加载?如何检查文档加载是否完成?
How is jQuery checking if the document is loaded? How it is checking that the document load is finished?
推荐答案
它们绑定到DOMContentLoaded事件(或在某些浏览器上为onreadystatechange).如果不支持DOMContentLoaded或由于其他原因不触发DOMContentLoaded,它们也可以回退到常规的load事件.在支持它的浏览器上,他们使用此调用:
They bind to the DOMContentLoaded event (or onreadystatechange on some browsers). They also have a fallback to the regular load event, in case the DOMContentLoaded isn't supported or not fired for other reasons. On browsers supporting it, they use this call:
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
在IE< 9上:
On IE <9:
document.attachEvent( "onreadystatechange", DOMContentLoaded);
这些调用中DOMContentLoaded
的第二个实例是它们自己的函数-实际上是对源代码中bindReady
上方的ready
函数的引用.此功能将通过检查document.body
来检查DOM树是否已完成.如果尚不存在,则等待一毫秒(使用setTimeout),然后再次检查.当document.body存在时,它们遍历您设置的回调列表.
The second instance of DOMContentLoaded
in these calls is their own function - actually a reference to the ready
function right above bindReady
in the source code. This function will check that the DOM tree is actually done by checking for document.body
. If it doesn't exist yet, they wait a millisecond (using setTimeout) and check again. When document.body exists, they traverse the list of callbacks you've set.
这篇关于jQuery如何“准备好文档"?功能正常吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!