且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查文档是否准备就绪?

更新时间:2023-11-28 15:58:28

这是没有记录,我不觉得,但如果你看一下jQuery的code为的$(document )。就绪

This isn't documented, I don't think, but if you look at the jQuery code for $(document).ready:

// If the DOM is already ready
if ( jQuery.isReady ) {
  // Execute the function immediately
  fn.call( document, jQuery );
} // ...

因此​​,对于可能会改变,你可以用一种方式 $。isReady时 jQuery.isReady

有一个更好的办法是使用 $(文件)。就绪排队。例如:

A better way would be to use $(document).ready in line. e.g.:

function myClickHandler(event) {
  // do stuff

  $(document).ready(function() {
    // Do this immediately if DOM is loaded, or once it's loaded otherwise.
  }
}

从本质上讲,这里采用现成的功能作为一个后卫。相反的if语句,你可以使用现成的功能。当然,准备函数,它的将会的运行,一旦DOM被加载的行为。如果你的行为只是想要的东西发生,如果它的加载,但从来没有这样做,如果DOM尚未加载,然后用上面的标志,或者设置你自己的,就是***​​的路要走。设置你自己的:

Essentially, this uses the ready function as a guard. Instead of an if statement, you use the ready function. Of course, the ready function has the behavior that it will run once the DOM is loaded. If your behavior is only wanting something to happen if it's loaded, but never doing it if the DOM isn't loaded yet, then using the flag above, or setting your own, is the better way to go. Setting your own:

$(document).ready(function() {
  window.domIsReady = true;
}

if (window.domIsReady) {
  // do stuff
}

创建你自己可能会更好,因为 jQuery.isReady 似乎并没有被记录,因此可能不支持,并且可能在任何时间被改变。

Creating your own is probably better, since jQuery.isReady doesn't seem to be documented, and therefore probably isn't supported and may be changed at any time.