Right after my script is loaded I am making an Ajax request to get some translations. This should always return after the document is ready since I am loading my scripts at the bottom of the page, but I am still curious if it would be possible to get a Deferred Object on the document ready state.
That way it would be possible to make sure that both, the document is ready and the Ajax call returned successfully before doing anything else, e.g. like this:
$.when( $.ajax('translations'), document.ready())
.then(function(){
// Start doing stuff here
});
You can associate a deferred object with the document using data(), and resolve() it in your
ready
handler. This way, you should be able to use the stored deferred object with $.when():My version is:
jQuery's
when
is not a proper promise. You can force it into one like this:Usage:
It happens to resolve with
$
so that's kind of convenient too.Alternative implementation:
Update for reference (2015):
This is available in current versions of jQuery:
It is also simple to convert to a stream using highlandjs:
Here's a cleaned up version of ircmaxell's comment:
edit
Some clarification to stop the incorrect edits:
Passing a function to the jquery object (e.g.
$(some_func)
) is the same as$(document).ready(some_func)
.Therefore, the
$(doc_ready.resolve);
line is just shorthand for something like this:Try this: