I want my handler of the ready
event will fire after all other handlers are done.
It's extremely handy for manipulating plugins' undesired actions.
If I write my handler after all others, it only guarantees it will fire after all others fired, not finished:
$(function() {
setTimeout(function() { alert('other handler'); }, 500);
});
$(function() { alert('my handler'); });
In that code, my handler alerted first.
I read that before jQuery version 1.4
the readyList
was public. so in version 1.7
I have no idea how I can tell that my handler is the last handler or not.
An idea could be creating an array of
deferred
to use inside every ready function (except the last one), resolving each one when the snippet has completed.Then, in the last ready function you could simply check the promise resolution with
$.when
and then execute some other code: e.g.See fiddle in action here: http://jsfiddle.net/DXaw5/
I usually use the following pattern, simply keepig a counter of finished async functions:
The same in coffeescript:
(We call the same function for 10 times to keep the example simple, while in reality you may of course call different functions, but the same idea apply; in callback function you check the counter.)
If the idea is that you don't control the other ready handlers, then given your example where another handler used a
setTimeout
, you can never actually know (without inspecting the other code) if your code will run after all other code.The
readyList
wouldn't help even if it was public, because in your example, the handler with thesetTimeout
will be removed from thereadyList
long before thesetTimeout
handler runs. ThereadyList
Array doesn't have any control over that sort of asynchronous code either.So if you don't control (can't modify) the other code, then I really don't have a solution. But if the other code is just long running, but not asynchronous, then there wouldn't be any issue, because if your code is the last
.ready()
handler assigned, it shouldn't matter how long the other handlers take to execute. If their code is synchronous, it will force yours to wait until they're complete. It's just that if they're using asynchronous code, like yoursetTimeout
example, then there's nothing you can do short of examining the other code, and modifying yours to make sure it fires last.I don't know if it is possible for you to create a queue for all the functions like
You can use something like this:
An example: