javascript - 当在同一个 HTML 页面上使用的两个 JavaScript 文件中有两个 jQuery $(document).ready 调用时会发生什么?

标签 javascript jquery html dom document-ready

我有一个关于 jQuery $(document).ready

的问题

假设我们有一个包含 2 个 JavaScript 文件的 HTML 页面

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

现在让我们假设在这两个脚本文件中,我们有如下$(document)

script1.js 中:

$(document).ready(function(){
    globalVar = 1;
})

script2.js 中:

$(document).ready(function(){
    globalVar = 2;
})

现在我的问题是:

  1. Will both these ready event function get fired ?
  2. If yes, what will the order in which they get fired, since the document will be ready at the same time for both of them?
  3. Is this approach recommended OR we should ideally have only 1 $(document).ready ?
  4. Is the order of execution same across all the browsers (IE,FF,etc)?

谢谢。

最佳答案

  1. Will both these ready event function get fired ?

是的,他们都会被解雇。

  1. what will the order in which they get fired, since the document will be ready at the same time for both of them?

以它们出现的方式(从上到下),因为 ready 事件将被触发一次,并且所有事件监听器将陆续收到通知。

  1. Is this approach recommended OR we should ideally have only 1 $(document).ready ?

这样就可以了。如果您可以将它们放在同一个 block 代码中,那么管理起来会更容易,但仅此而已。 更新:显然我忘了说,如果在多个文件中执行此操作,将会增加 JavaScript 代码的大小。

  1. Is the order of execution same across all the browsers (IE,FF,etc)?

是的,因为 jQuery 手头有跨浏览器规范化。

关于javascript - 当在同一个 HTML 页面上使用的两个 JavaScript 文件中有两个 jQuery $(document).ready 调用时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6435868/

相关文章:

javascript - 按 Enter 重新加载页面而不是提交表单

javascript - Classic Asp 如何将生成的 HTML 保存到服务器上的文本文件中?

javascript - 阻止网站请求外部 src

javascript - 如何在不更改原始参数数组的情况下操作传递给函数的 JavaScript 数组?

javascript - d3 SVG文本元素background-color与getBBox()的顺序错误

javascript - html 不会在部分 View 中呈现

jquery - 自举流体布局和全高div

javascript - 采用 HTML 形式并将值传递给 node.js 函数中的变量

javascript - 在浏览网站时保持与服务器的永久连接

html - 从NSString删除损坏的HTML标记