1

Possible Duplicate:
Can you have multiple $(document).ready(function() sections?

Is it OK to have multiple calls to $(document).ready on the same page? If so how is the order that the code is run in resolved and does this have any implications

I am using jQuery in my rails app. I have several levels of javascript used through the application, all of which use jQuery.

For example I have some default code that fades out Flash Notices in my application.js I have a projects.js file that is included in all Project model views, and I have a project/edit.js that is included only in the view rendered by the edit action.

In all three js files I am using:

$(document).ready
{
   //Do something
}
Community
  • 1
  • 1
Undistraction
  • 42,754
  • 56
  • 195
  • 331
  • yes.....its ok to have multiple calls to $(document).ready . and the order of code run is depends on which js is loading first. – Priyank Patel May 17 '12 at 10:22
  • @ManseUK That's a good link, but I think this question is slightly different. – Undistraction May 17 '12 at 10:28
  • @1ndivisible thats why it has the word "Possible" on the front of the comment – Manse May 17 '12 at 10:30
  • You can also check the accepted answer in this question http://stackoverflow.com/questions/3934570/order-of-execution-of-jquery-document-ready – Prasenjit Kumar Nag May 17 '12 at 10:31
  • @ManseUK Yes. I understand that. I was simply outlining why I don't think it's a duplicate. That's why I used the words "I think" in my comment. – Undistraction May 17 '12 at 10:56
  • @1ndivisible we could go on forever :-) ... the answers below give you what you need and its not been closed so all is good ... – Manse May 17 '12 at 10:57

3 Answers3

6

It's fine.

The execution order will be in the same order they were used.

First in First Out

jQuery has an internal queue called readyList storing all the callbacks for the ready event. When you call the ready function with a callback is simply add it to the queue and fire the whole queue when the DOM is ready.

Looking at the jQuery source code can tell you that easily:

source code:

// The deferred used on DOM ready
readyList,
...
...

ready: function( fn ) {
    ...
    // Add the callback
    readyList.add( fn );

    return this;
}
gdoron
  • 147,333
  • 58
  • 291
  • 367
1

They run the same order they were attached and it's fine to do so. However, you could do a shorter equivalent to lessen function calls since $(document).ready() by itself is 2 function calls

$(function(){
    //document is ready
});
Joseph
  • 117,725
  • 30
  • 181
  • 234
0

Calls to $(document).ready in jQuery are executed in the order that they are defined. More info here http://docs.jquery.com/Tutorials:Multiple_$(document).ready()

Luca
  • 4,223
  • 1
  • 21
  • 24