Its right from UI design point of view to show user some kind of progress in case site or application is busy with some internal processing. Especially with AJAX requests, because they take time!
In jQuery its very easy to hook all AJAX requests into one start/stop functions, so there is no need to show and hide progress indicator on each $.ajax request.
I make usage of nice spin.js library, native JavaScript implementation of configurable spinner.
Code below is pretty self-explaning. It uses jQuery ajaxStart and ajaxStop hooks to show and hide spinner. Put this code into external file and just put a link on every page and thats it.
// Creating spinner see <a href="http://fgnass.github.com/spin.js/">http://fgnass.github.com/spin.js/</a> for configuration wizzard
var opts = {
lines: 13, // The number of lines to draw
length: 7, // The length of each line
width: 4, // The line thickness
radius: 10, // The radius of the inner circle
rotate: 0, // The rotation offset
color: '#efefef', // #rgb or #rrggbb
speed: 0.75, // Rounds per second
trail: 50, // Afterglow percentage
shadow: true, // Whether to render a shadow
hwaccel: false, // Whether to use hardware acceleration
className: 'spinner', // The CSS class to assign to the spinner
zIndex: 2e9, // The z-index (defaults to 2000000000)
top: 'auto', // Top position relative to parent in px
left: 'auto' // Left position relative to parent in px
};
var spinner = new Spinner(opts);
var ajax_cnt = 0; // Support for parallel AJAX requests
// Global functions to show/hide on ajax requests
$(document).ajaxStart(function() {
$('<div id ="spinner_center" style="position:fixed;top:70px;left:49%;"> </div>').appendTo('body');
spinner.spin($('#spinner_center')[0]);
ajax_cnt++;
});
$(document).ajaxStop(function() {
ajax_cnt--;
if (ajax_cnt <= 0) {
spinner.stop();
$('#spinner_center').remove();
ajax_cnt = 0;
}
});
I added ajax_cnt variable when I faced several AJAX requests being called at once, now it counts them and correctly hides the spinner!