我有一个关于 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;
})
现在我的问题是:
- Will both these ready event function get fired ?
- 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?
- Is this approach recommended OR we should ideally have only 1 $(document).ready ?
- Is the order of execution same across all the browsers (IE,FF,etc)?
谢谢。
最佳答案
- Will both these ready event function get fired ?
是的,他们都会被解雇。
- what will the order in which they get fired, since the document will be ready at the same time for both of them?
以它们出现的方式(从上到下),因为 ready 事件将被触发一次,并且所有事件监听器将陆续收到通知。
- Is this approach recommended OR we should ideally have only 1 $(document).ready ?
这样就可以了。如果您可以将它们放在同一个 block 代码中,那么管理起来会更容易,但仅此而已。 更新:显然我忘了说,如果在多个文件中执行此操作,将会增加 JavaScript 代码的大小。
- 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/