多个DOM Ready?

时间:2013-01-06 21:29:52

标签: javascript jquery

  

可能重复:
  JQuery - multiple $(document).ready …?

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

$(function() {

});

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

$(function() {
      // First Script
});

$(function() {
      // Second Script
});

//etc. 

或者可以将multplie脚本放在一个脚本中吗? IE:

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

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

3 个答案:

答案 0 :(得分:7)

你的脚本中可能有多个document.ready处理程序,jQuery会在执行之前将它们合并为一个。但实际上没有必要拥有许多document.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>

答案 1 :(得分:4)

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

然而,它可能对组织有用。

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

答案 2 :(得分:0)

您可以将所有脚本/函数包装在一个ready事件中,或者只需将所有脚本放在html之后,然后避免等待ready事件,因为此时DOM已经加载了。

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