I know calls to $(function(){ }) in jQuery are executed in the order that they are defined, but I'm wondering if you can control the order of the queue?
For example, is it possible to call "Hello World 2" before "Hello World 1":
$(function(){ alert('Hello World 1') });
$(function(){ alert('Hello World 2') });
The question is whether or not it's possible... I already know it goes against best practice ;)
You can use jQuery promise to achieve something like this.
Following is an example where jQuery.ready.promise helps managing the order of execution of DOM Ready Blocks:
In the following example, the first DOM Ready block is trying to access the height of the test div which is appended to the body in a later DOM Ready block. As in the Fiddle it fails to get it.
Fiddle: http://jsfiddle.net/geektantra/qSHec/
In the following example, it is doing exactly the same as the example before using jQuery.ready.promise. As in the Fiddle it works as required.
Fiddle: http://jsfiddle.net/geektantra/48bRT/
It can be done, but not easily. You'd have to hack jQuery itself, probably here. Before jQuery starts calling these functions inside the
while
loop, you'd have to add code to inspect thereadyList
array and re-order the elements according to your preference.Those functions are added to a private array
readyList
, so I'd say it isn't accessible for manipulation.http://github.com/jquery/jquery/blob/master/src/core.js#L47
here is how you would go about doing it:
You can read more about it here