Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple DOM Ready? [duplicate]

Possible Duplicate:
JQuery - multiple $(document).ready …?

I have my JS code that is using jQuery within the jQuery Document Ready IE:

$(function() {

});

I am running multiple jQuery scripts on the page and all are contained within one $(function() { }); is there any reason I should break the scripts into multiple ready handlers? IE:

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

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

//etc. 

or is it okay to have multplie scripts within one? IE:

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

I assume one is just fine but I want to ensure there are no reasons I should use multiple ones.

like image 526
L84 Avatar asked Dec 20 '22 11:12

L84


2 Answers

You could have multiple document.ready handlers in your script(s), jQuery will merge them into a single one before executing anyway. But it's really not necessary to have many document.ready handlers. One is enough. And if you put your scripts always at the end of your DOM, just before the closing </body> tag you don't need to use any document.ready handlers.

For example:

<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>
like image 153
Darin Dimitrov Avatar answered Jan 03 '23 13:01

Darin Dimitrov


It makes absolutely no difference with regards to how it works.

However, it can be useful for organision.

On the other hand, it means more jQuery has to run.

like image 44
Niet the Dark Absol Avatar answered Jan 03 '23 13:01

Niet the Dark Absol