Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I get a jQuery Deferred on document.ready()?

Tags:

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 }); 
like image 240
Daff Avatar asked May 30 '11 13:05

Daff


People also ask

Can jQuery be deferred?

The jQuery. Deferred method can be passed an optional function, which is called just before the method returns and is passed the new deferred object as both the this object and as the first argument to the function. The called function can attach callbacks using deferred.

Can I use jQuery without document ready?

It is in no way required. All it does is make sure that the DOM is loaded before trying to query for and use the elements inside the DOM (usually after dom is ready and before body. onload fires). You can use jquery perfectly fine without it.

Is document ready JavaScript or jQuery?

$( document ). ready() ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside $( window ).

Is jQuery document ready deprecated?

// Handler for . ready() called.


2 Answers

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():

$(document).data("readyDeferred", $.Deferred()).ready(function() {     $(document).data("readyDeferred").resolve(); });  $.when($.ajax("translations"), $(document).data("readyDeferred"))  .then(function() {     // Start doing stuff here. }); 
like image 135
Frédéric Hamidi Avatar answered Sep 21 '22 14:09

Frédéric Hamidi


Here's a cleaned up version of ircmaxell's comment:

(function() {   var doc_ready = $.Deferred();   $(doc_ready.resolve);   $.when(doc_ready, $.ajax('translations')).then(function() {     console.log("done");   }); })(); 

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:

$(document).ready(function() {   doc_ready.resolve() }); 
like image 45
zaius Avatar answered Sep 17 '22 14:09

zaius