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 - 第二次单击浅灰色弹出窗口时,Azure Media Player 不播放视频

javascript - 第一次后附加到 SourceBuffer 的 MediaSource 不起作用

javascript - 检测父div内子div的类,然后将class或id添加到父div

jquery - "#orderedlist > li"选择器

html - CSS 链接背景图片不显示

javascript - 在一定时间后随机更改 wordpress 标题图片

javascript - 在javascript问题中读取xml

javascript - 我在让 jquery 根据类名插入 html 时遇到问题

javascript - 在另一个文件中添加JS src

php - 如何使用php将图片存储到mysql数据库中