1

I want to check if all ajax requests have completed and only then interact with element on a web page. Hence I opened chrome browser's developer console. And after entering url in search bar and hitting ENTER key, in console I keep hitting $.active multiple times and in results most of the time I can see returned value as 0 but some time as 1

I hit $.active command with hand hence I am not able to see consistent result all the time. Is there any java script code which I can enter in console and after hitting it, $.active command will be hit one by one till the number of times mentioned?

Alpha
  • 13,320
  • 27
  • 96
  • 163
  • 3
    Having a hard time finding out what `$.active` is, I don't see it [here](https://developers.google.com/web/tools/chrome-devtools/console/utilities) and it's hard to google, do you have a reference? – CertainPerformance Nov 29 '19 at 10:22
  • I got it from one of the answers of https://stackoverflow.com/questions/1822913/how-do-i-know-if-jquery-has-an-ajax-request-pending – Alpha Nov 29 '19 at 10:26
  • 1
    You're asking the wrong question (see here: [xy problem](http://xyproblem.info/)); what you want to do is run multiple asynchronous requests and run some code after all of them have finished. JS has `Promise.all` for that, and jQuery has [`.when`](https://api.jquery.com/jQuery.when/) edit: are you saying the website (not you) is running those ajax requests, and you are simply trying to wait for them to finish? –  Nov 29 '19 at 10:26

1 Answers1

0

If $ is jQuery, you can add an ajaxComplete callback, and check if $.active inside:

$(document).on('ajaxComplete', () => {
  Promise.resolve().then(() => {
    if (!$.active) {
      console.log('All done');
    }
  });
});

It's not a single line of code, but it should work. (You can test it by running this in the console, then opening your inbox or reputation record in Stack Overflow's topbar. An ajax request will be sent out, and when it's complete, ajaxComplete will run, and $.active will get set to 0)

The Promise.resolve().then is needed because $.active gets decremented only after the ajaxComplete callback runs.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320