简体   繁体   中英

Detect when all JQuery / JavaScript / Ajax calls are finished

I want to be able to inject a script into a page that will detect if anything is still 'going on' or not. When I say going on, I mean scripts still in execution, Ajax calls in process, or the page not being fully loaded yet. The reason being I need to check if various elements exist (via JQuery) and then do something with it. I'm trying to get this as generic as possible, as I've be injecting this in to pages with all sorts of stuff in them.

Obviously using .ready will tell me when the page is loaded:

 $( document ).ready(function() {...}); //Super easy!

And I can detect if an Ajax call is going on with something like:

var AjaxInProgress= function (){return jQuery.active!=0;};

$( document ).ajaxStart(function() {
  console.log('Ajax stuff happening!');
});
$( document ).ajaxStop(function() {
  console.log('Ajax stuff finished!');
});

BUT... if these Ajax calls are happening synchronously I get results like:

 Ajax stuff happening!
 Ajax stuff finished!
 Ajax stuff happening!
 Ajax stuff finished!
 Ajax stuff happening!
 Ajax stuff finished!
 Ajax stuff happening!
 Ajax stuff finished!

So apparently there is JavaScript waiting for results from each Ajax call before firing off another one, and I get a 'false positive' after the first few because more is yet to happen.

Is there a way I can generically detect if all scripts have executing and nothing is waiting for an Ajax response? Obviously any solution would have to avoid a race condition, and it would not cater for long polling.

I've done this a while back. Take a look at this link: http://api.jquery.com/jQuery.when/

Basically, do this:

var xhr1 = $.ajax( "/page1.php" );
var xhr2 = $.ajax( "/page2.php" );
$.when( xhr1 , xhr2 )
     .then( myFunc, myFailure );

This would execute the function myFunc when both ajax requests are successful, or myFailure if either one has an error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM