Check when all Ajax Requests are complete - Pure JavaScript -
i know jquery's ajaxstop method.
$(document).ajaxstop(function() { //do });
is there way pure javascript if jquery not available?
could provide example if so?
cheers
very well, i'll bite (though not trying quite lazy on part):
from jquery docs:
whenever ajax request completes, jquery checks whether there other outstanding ajax requests. if none remain, jquery triggers ajaxstop event. , handlers have been registered .ajaxstop() method executed @ time.
so need? well: central api (a module of sorts) you'll use perform ajax requests. in module, you'll have keep track of pending requests, , remove them once requests have terminated.
if queue (so speak) empty, can check ajaxstop
queue registered callbacks, , invoke those.
a basic setup (pseudo-code) this:
var myajax = (function() {//create closure scope track ajax requests var activerequests = [], stopqueue = [], ajaxmodule = {},//the module createxhr = function(){};//function create xhr requests ajaxmodule.ajax = function(params, callback) { var xhr = createxhr(params), key = activerequests.length; activerequests.push(xhr);//add active array xhr.onreadystatechange = function() {//assign internal handler if (this.readystate === 4 && this.status === 200) { //invoke passed callback if request done callback.call(this, []);//pass params please activerequests.filter(function(e) { return e !== this; }, this);//define callback in closure, of course if (activerequests.length === 0) {//no more active requests stopqueue.map(function(callback) { callback();//invoke callbacks }); } } }; }; return ajaxmodule;//expose module }());
of course, you'll still have implement functions manage stopqueue callbacks, , you'll have implement reliable ajax module yourself, simple setup use.
Comments
Post a Comment