Multiple DOM Ready?

Multiple DOM Ready?

本文关键字:Ready DOM Multiple      更新时间:2023-09-26

可能重复:
JQuery-多个$(文档(。准备好了…?

我的JS代码在jQuery Document Ready IE:中使用jQuery

$(function() {
});

我在页面上运行多个jQuery脚本,并且所有脚本都包含在一个$(function() { });中。我有什么理由将脚本分解为多个现成的处理程序吗?IE:

$(function() {
      // First Script
});
$(function() {
      // Second Script
});
//etc. 

或者在一个脚本中包含多个tplie脚本可以吗?IE:

$(function() {
      // First Script
      //Second Script
      //etc. 
});

我认为一个很好,但我想确保没有理由使用多个。

脚本中可能有多个document.ready处理程序,jQuery在执行之前会将它们合并为一个处理程序。但是确实没有必要有很多文档。ready处理程序。一个就足够了。如果您总是将脚本放在DOM的末尾,就在关闭</body>标记之前,则不需要使用任何document.ready处理程序。

例如:

<html>
<head>
    <title></title>
    ... your CSS references come here
</head>
<body>
    ... the markup of the body comes here ...
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
        // you don't need to use any document.ready handlers here =>
        // you could directly write your scripts inline or reference them
        // as external resources. At this stage the DOM will be ready
    </script>
</body>
</html>

它的工作方式完全没有区别。

然而,它对组织是有用的。

另一方面,这意味着必须运行更多的jQuery。

您可以将所有脚本/函数封装在一个就绪事件中,也可以简单地将所有脚本放在html之后,然后避免等待就绪事件,因为此时DOM已经加载。

<html>
<head>
    <!-- Style sheets Go Here -->
</head>
<body>
    <!--HTML Goes Here -->
    <!-- Scripts Go Here -->
</body>
</html>