jquery是如何实现$(document).ready()的?

jquery是如何实现$(document).ready()

当然我可以阅读代码,但我正在寻找这个概念……

通常,它会检查浏览器是否已经将body元素加载到DOM树中,在这种情况下,它会执行cb()而不等待其他请求(图像……)

否则它会等待一段时间并重新检查..

概念: jQuery.ready

虽然JavaScript在呈现页面时提供了用于执行代码的加载事件,但在完全接收到所有资产(如图像)之前,不会触发此事件。 在大多数情况下,只要完全构造DOM层次结构,就可以运行脚本。 传递给.ready()的处理程序保证在DOM准备好后执行,因此这通常是附加所有其他事件处理程序并运行其他jQuery代码的最佳位置。 使用依赖于CSS样式属性值的脚本时,在引用脚本之前引用外部样式表或嵌入样式元素很重要。

它根据浏览器(IE,例如,不同)实现它,但是在一些特殊情况下,例如在加载DOM 之后调用它时。 (我不确定如何在查看来源的情况下回答这个问题)。

jQuery.ready的核心 (设置事件绑定的东西是):

 bindReady: function() { 

只绑定一次。

  if ( readyBound ) { return; } readyBound = true; 

确保处理 “DOM加载” 之后调用ready的情况。

  // Catch cases where $(document).ready() is called after the // browser event has already occurred. if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready return setTimeout( jQuery.ready, 1 ); } 

W3C标准事件模型。

  // Mozilla, Opera and webkit nightlies currently support this event if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); 

老派后备。

  // A fallback to window.onload, that will always work window.addEventListener( "load", jQuery.ready, false ); 

IE事件模型(也可能是Opera将使用它)。

  // If IE event model is used } else if ( document.attachEvent ) { // ensure firing before onload, // maybe late but safe also for iframes document.attachEvent("onreadystatechange", DOMContentLoaded); 

老派后备。

  // A fallback to window.onload, that will always work window.attachEvent( "onload", jQuery.ready ); 

在不同的环境中使其与IE一致地工作的更多行为。 请注意,事件绑定适用于’onreadystatechange’

  // If IE and not a frame // continually check to see if the document is ready var toplevel = false; try { toplevel = window.frameElement == null; } catch(e) {} if ( document.documentElement.doScroll && toplevel ) { doScrollCheck(); } } }, 

doScrollCheck在IE中设置一个“轮询”,只有在成功条件成功时才会调用处理程序。 有关详细信息,请参阅源代码(它使用IE的一个怪癖)。

快乐的编码。

它测试document.body是否不评估某些东西: http ://james.padolsey.com/jquery/#v=1.5.0&fn=jQuery.ready