javascript - $(document).ready(...) 的调用堆栈是如何组装的?

标签 javascript jquery

<分区>

当我在大型网站上工作并包含一堆外来的 JS 文件并尝试调试内容时,我总是对此感到困惑。

如果我有

<script type="text/javascript">
     $(document).ready(function(){
          console.log("foo");
     });
     $(document).ready(function(){
          console.log("bar");
     });
</script>

那么这是否保证 console.log("bar")console.log("foo") 之后立即触发???如果我有也是一样吗

<script type="text/javascript" src="script1.js"></script> 
<script type="text/javascript" src="script2.js"></script>

其中 script1.js

     $(document).ready(function(){
          console.log("foo");
     });

script2.js组成

     $(document).ready(function(){
          console.log("foo");
     });

当我将 window.onloaddocument.onload 添加到组合中时会发生什么,例如

<script type="text/javascript">
     $(document).ready(function(){
          console.log("foo");
     });
     window.onload = function() { console.log("John Skeet"); };
     $(document).ready(function(){
          console.log("bar");
     });
     window.onload = function() { console.log("Bjarne Stroustrup"); };
</script>

??????

这里有人可以解释,或引导我查看解释这些“在其他所有事件之后触发”函数如何堆叠的规则的文档吗?

最佳答案

它们同步运行。

也就是说它们是按顺序运行的:

1. console.log("foo"); //this gets first logged
2. console.log("John Skeet"); //this gets logged after "foo"
3. console.log("bar"); //this gets logged after "John Skeet"
4. console.log("Bjarne Stroustrup"); //this gets logged after "Bjarne Stroustrup" 

因此,除非您有异步代码,否则它们会同步运行。

例如:

$(document).ready(function(){
  setTimeout(function(){
     console.log('foo');
  }, 1000);
});
$(document).ready(function(){
  setTimeout(function(){
     console.log('bar');
  }, 2000);
});

在我的代码示例中,我提供了异步代码(setTimeout 方法),首先记录“bar”,然后记录“foo”。

因此,文档就绪处理程序与排序无关紧要,但与其同步/异步代码有关。

看看jquery的代码你可能就清楚了:

jQuery.fn.ready = function( fn ) {
    // Add the callback
    jQuery.ready.promise().done( fn );

    return this;
};

因此,所有就绪的处理程序都被推送到 promise,然后调用其函数。

关于javascript - $(document).ready(...) 的调用堆栈是如何组装的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29657910/

相关文章:

javascript - clearInterval 对我不起作用

javascript - 获取矩形以使用 Raphael 和 Handdrawn.js 填充 svg

javascript - Typescript ,'NodeListOf<Element>' 不是数组类型也不是字符串类型

javascript - onEdit、breakApart 未按计划工作

javascript - 跨域页面刷新

javascript - 是否最好避免为 Ajax 响应直接返回 HTML?

javascript - jQuery 数据给我 undefined

javascript - 突出显示旁边的 td 或 tr

javascript - .not() 不工作

javascript - 如何在悬停时显示最近的 div?