Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
556 views
in Technique[技术] by (71.8m points)

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

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
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...