javascript loading before jQuery Ready?

789 views Asked by At

JS newb here and was handed a project to take over. I have a situation that I was able to get working (and took me forever to do so), but I don't understand the JS internals behind it. Can someone shed light on this?

I have a JS file with two different type of function blocks inside of a js file that I'll call last.js b/c it is the last file listed:

  1. Immediate function that is passed the jQuery object
(function ($) {
...
}(jQuery));
  1. And right after that you have the standard jQuery doc load code:
$(function () {
...
});

This JS file is the last one referenced on my page and I assume it will be the last one called/loaded when the page executes. But that isn't quite the case. The immediate function (1) is called first. Next, there jqueryvalidation.js file is loaded and executed. Finally, the jQuery ready() function in last.js is called.

So this effectively runs the immediate function before my other js libraries, then it loads/runs the other js files in order and lastly it comes back to my last.js file and finishes it. How can the last file in the list be called before my jqueryvalidation.js file? And the immediate function is passed jQuery, so jQuery would have had to already be loaded and the page should be ready at that time.

For me to use jqueryvalidation.js I have to put my custom validation code in the immediate window. If I put it in the jQuery ready function it gets called after the validation code has parsed the page and doesn't do anything.

Why would these two functions that are in the same js file have a completely different order of execution?

1

There are 1 answers

0
gen_Eric On BEST ANSWER

$(function(){}) is shorthand for $(document).ready(function(){}), which it means it's not executed until the document is loaded.

So, what's happening here is your code is running and when it hits $(function(){}), it adds a function to the event queue, then the rest of the code runs.

It then goes onto the next <script> tag and so on until it's parsed the page. Once the DOM is ready, then your function runs.