什么时候调用document.ready()?

时间:2016-03-21 23:43:22

标签: javascript jquery

在下面的解析阶段,

enter image description here $ document.ready()什么时候执行?

2 个答案:

答案 0 :(得分:8)

当HTML加载时,DOM /文档对象模型被加载时的简单anwser ..

Docs

  

$(document).ready()中包含的代码只会在页面上运行一次   文档对象模型(DOM)已准备好执行JavaScript代码。

我在这里也很好地解释了:

https://discuss.codecademy.com/t/window-onload-vs-document-ready/19000

我在哪里说:

jQuery document.ready将在HTML准备就绪时运行您的代码,但在图像和其他资源完成之前。这是您可以使用JavaScript更改DOM的最早时间,因此它被广泛使用。在像Google Chrome这样的现代浏览器中,它被DOMContentLoaded3取代。再次更多信息在这里。

所以通过你的照片: enter image description here

当Dom已经“完成”加载时, $ document.ready(fn)将在交互式面的开始处加载...

答案 1 :(得分:1)

  

$ document.ready()什么时候执行?

.ready()可以多次执行

  

.ready( handler )
  退货:jQuery
  描述:指定在DOM完全加载时要执行的函数。

     

如果在.ready()初始化后调用DOM,则为新   传入的处理程序将立即执行。

     

.ready()方法只能在匹配的jQuery对象上调用   当前文档,因此可以省略选择器。



n = -1;

function ready() {
  document.getElementsByTagName("p")[0].textContent += "ready " + ++n + "\n";
}

$(document).ready(ready);

$(document).ready(function() {
  ready();
  $(document).ready([function() {
    ready()
  },
    function() {
      $(document).ready(function() {
        ready();
        $(document).ready([
          function() {
            ready()
          }, function() {
          ready()
          if (n === 5) $(document).ready(function() {ready()})
        }]);
      
      })
    }
  ])
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>

<body>
  <p></p>
</body>
&#13;
&#13;
&#13;

请参阅ready.js

处的soruce
if ( document.readyState === "complete" ||
    ( document.readyState !== "loading" && !document.documentElement.doScroll ) ) {

    // Handle it asynchronously to allow scripts the opportunity to delay ready
    window.setTimeout( jQuery.ready );

} else {

    // Use the handy event callback
    document.addEventListener( "DOMContentLoaded", completed );

    // A fallback to window.onload, that will always work
    window.addEventListener( "load", completed );
}
相关问题