What happens when you have two jQuery $(document).ready calls in two JavaScript files used on the same HTML page?

testndtv picture testndtv · Jun 22, 2011 · Viewed 20.8k times · Source

I have a question on jQuery $(document).ready

Let's say we have a HTML page which includes 2 JavaScript files

<script language="javascript" src="script1.js" ></script>
<script language="javascript" src="script2.js" ></script>

Now let's say in both these script files, we have $(document) as follows

Inside script1.js:

$(document).ready(function(){
    globalVar = 1;
})

Inside script2.js:

$(document).ready(function(){
    globalVar = 2;
})

Now my Questions are:

  1. Will both these ready event function get fired ?
  2. 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?
  3. Is this approach recommended OR we should ideally have only 1 $(document).ready ?
  4. Is the order of execution same across all the browsers (IE,FF,etc)?

Thank you.

Answer

Shef picture Shef · Jun 22, 2011
  1. Will both these ready event function get fired ?

Yes, they will both get fired.

  1. what will the order in which they get fired, since the document will be ready at the same time for both of them?

In the way they appear (top to bottom), because the ready event will be fired once, and all the event listeners will get notified one after another.

  1. Is this approach recommended OR we should ideally have only 1 $(document).ready ?

It is OK to do it like that. If you can have them in the same block code it would be easier to manage, but that's all there is to it. Update: Apparently I forgot to mention, you will increase the size of your JavaScript code if you do this in multiple files.

  1. Is the order of execution same across all the browsers (IE,FF,etc)?

Yes, because jQuery takes the cross-browser normalization at hand.