0

I have this code:

$.when($.post(...)).then(function () {
  ...
});

Which I want to combine with $(document).ready(...); so that the request starts when the page initializes, and everything inside the .then function runs when both the page and the POST request have finished loading.

How can I do this?

Lucas
  • 16,930
  • 31
  • 110
  • 182

3 Answers3

1

jQuery will produce a promise for when the DOM is loaded. So, you can use $.when() to wait for both promises. As such, you can do this:

$.when($.post(...), jQuery.ready.promise()).then(function(result) {
    // code here
    // result[0] is ajax result
});

This will let you launch your ajax call immediately, but then process its results only when the page is ready.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
0

I just figured this out.

Apparently $(document).ready(function () { }) doesn't just set an event handler, but also runs the code inside immediately if the page has already loaded. So now I'm just using this:

$.post(...).then(function () {
  $(document).ready(function () {
    ...
  });
});

This allows for the code to be run only if the POST request has completed, and the page has finished loading.

Lucas
  • 16,930
  • 31
  • 110
  • 182
  • No need for `$.when()` in this code. It is superfluous since `$.post()` has a `.then()` handler all on its own. Also, see how `$.when()` can be used in my answer. – jfriend00 May 10 '16 at 08:12
-1

You, can set either some time interval like

setTimeout(function(){ //do something here }, 3000);

inside .then or check whether some div of your page is exist inside your page like

$('#someDiv') !== null
Chetan Hirapara
  • 644
  • 1
  • 9
  • 29
  • Using a timer in this way is just a "guess" for when other code will be done and should pretty much never be done this way. – jfriend00 May 10 '16 at 08:14