End Loose Ends

March 2012 Entries

Dead Simple Ajax Progress Spinner

Here is a drive-by post for anyone that wants a simple way to show spinners during an AJAX requests. jQuery allows you to define AJAX pre-filters which enable you to do funky things before and after AJAX requests. The following snippet enables you to pass a jQuery selector as a "spinner" option to jQuery.ajax. It will automatically show the element after 500 ms and will hide it when the request is complete. If the request takes less than 500 ms, it won't show the spinner at all.
jQuery.ajaxPrefilter(function (options, originalOptions, jqXHR) {
  if (options.spinner) {
    var spinner = jQuery(options.spinner);
    if (spinner && spinner.length > 0) {
      var timeoutId = setTimeout(function () { spinner.show(); }, 500);
      jqXHR.always(function () {
        clearTimeout(timeoutId);
        spinner.hide();
      });
    } else {
      console.log('Found spinner parameter, but couldn\'t find the specified element.');
    }
  }
});
Using this pre-filter is a snap. Just pass it as an option to jQuery ajax as follows:
  jQuery.ajax({
    url: '/items/1',
    success: display,
    spinner: '#loadSpinner'
  });
The nice thing about this approach is that it lets you handle this uniformly across your application. Despite this, it gives you the flexibility of having multiple spinners in different locations.