I'm using the following mockup to show my loading spinner while doing AJAX requests in my jQuery code:
jQuery.ajaxSetup({
beforeSend: function() {
$('#loader').show()
},
complete: function(){
$('#loader').hide()
},
success: function() {
$('#loader').hide()
}
});
This code works perfectly fine for me!
Just one problem:
Some requests are just very simple and fast, so the loading spinner is just shown for a couple of millisecs. That of course isn't very pretty.
So I tried using setTimeout()
to display the loading spinner slightly delayed. I want it to only pop up if the AJAX requests takes at least, let's say 100ms, but it didn't work.
So I need some code to delay the loading spinner as I explained above, so it ONLY pops up while doing "longer" AJAX requests!
Parsing JSON was 10 times faster than parsing XML! When it comes to making AJAX behave like a desktop application, speed is everything, and clearly, JSON is a winner. Of course, you might not always have control of the server-side that's producing data for your AJAX application.
There are two different types of issues that can cause admin-ajax. php slow server responses. The first is a backend CPU issue and the second is more of a frontend issue where you will notice third party plugins polling this file in your website speed tests.
Basically, ajax request as well as synchronous request sends your document cookies automatically.
Just because a plugin uses Ajax doesn't mean that it'll slow down your site. Usually, Admin Ajax loads towards the end of the page load. Also, you can set Ajax requests to load asynchronously, so it can have little to no effect on the page's perceived performance for the user.
This is how I resolved your mentioned functionality
var loading;
$("#loader").hide();
jQuery.ajaxSetup({
beforeSend: function() {
loading= setTimeout("$('#loader').show()", 300);
},
complete: function(){
clearTimeout(loading);
$("#loader").hide();
},
success: function() {
alert("done");
}
});
This is an old question but I've found a much nicer and elegant approach. jQuery exposes a variable $.active
which is the number of currently active ajax requests. The value of this increases before ajaxSend
and decreases after ajaxComplete
.
With that in mind, all we need to do is show the spinner when ajaxSend
is fired and $.active == '1'
and hide the spinner when ajaxComplete
is fired and $.active == '1'
. Here's my code which is currently working flawlessly.
$(document).ajaxSend(function(event, request, settings) {
$.active == '1' ? $('#spinner').show() : '';
});
$(document).ajaxComplete(function(event, request, settings) {
$.active == '1' ? $('#spinner').hide() : '';
});
Hope this helps someone.
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