I have a page that has a tab set. Each of the tabs is loaded by the jQuery .load()
function.
I want to display a loading animation that disappears when all of the ajax requests are finished. However, document.ready()
has only provided me with limited success.
How can I ensure that all ajax requests are completed before executing the code to hide the loading animation?
The ajaxStop() method specifies a function to run when ALL AJAX requests have completed. When an AJAX request completes, jQuery checks if there are any more AJAX requests. The function specified with the ajaxStop() method will run if no other requests are pending.
The ajaxComplete() method specifies a function to be run when an AJAX request completes. Note: As of jQuery version 1.8, this method should only be attached to document. Unlike ajaxSuccess(), functions specified with the ajaxComplete() method will run when the request is completed, even it is not successful.
There is a requirement to make multiple AJAX calls parallelly to fetch the required data and each successive call depends on the data fetched in its prior call. Since AJAX is asynchronous, one cannot control the order of the calls to be executed.
.ajaxStop(handler)
Documentation here: http://api.jquery.com/ajaxStop/
$(document).ready(function () {
$(document).ajaxComplete(function () {
alert('Completed');
});
});
ajaxComplete
Per the documentation:
$('.log').ajaxComplete(function() {
$(this).text('Triggered ajaxComplete handler.');
});
Use the callback
argument to .load()
, setting a flag or increasing a counter in the callback function. Once all flags are set or the counter reaches the number of tabs, you know all tabs have been loaded, and you can remove the animation.
In pseudocode that might or might not be valid JavaScript:
loadedTabs = 0;
function onLoad() {
for (int i = 0; i < numTabs; ++i) {
tabs[i].load(tabUrl(i), tabLoaded);
}
}
function tabLoaded() {
++loadedTabs;
if (loadedTabs == numTabs)
loadingAnimation.display = 'none';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With