Global AJAX Loading Spinners

Many sites include what are known as AJAX Spinners. They are little graphics that show up on a web page that show something is happening behind the scenes. This is most commonly used when an AJAX request is being made and the end-user is waiting for a response.

There are many different ways you can make this happen.

One is to show and hide the spinner inside each AJAX method. Another is to show and hide the spinner inside the jQuery $.ajaxSetup configuration.

If you load individual spinners for each call this is a pain and can be cluttering. If you load a common spinner you can end up hiding it before a parallel request is finished unless you look at a queue, which is also a pain.

One easy way around all this confusion is to use jQuery’s global AJAX handlers: .ajaxStart and .ajaxStop (also look at .ajaxError)

First setup a common spinner container and graphic.

<style>
#ajaxSpinnerContainer {height:11px;}
#ajaxSpinnerImage {display:none;}
</style>

<div id="ajaxSpinnerContainer">
<img src="/images/ajax-loader.gif" id="ajaxSpinnerImage" title="working...">
</div>

One great place to generate these spinners is ajaxload.info.

The next step is to show the spinner when any AJAX request has begun and hide it when all AJAX requests have completed.

$(document)
.ajaxStart(function(){
    $("#ajaxSpinnerImage").show();
})
.ajaxStop(function(){
    $("#ajaxSpinnerImage").hide();
});

This quick and easy method avoids all the other headache associated with all the other techniques out there as long as you want the spinner shown in a single container.

#ajax, #jquery, #spinner

jQuery Templates

I decided to dig into the new official jQuery Template Plugin developed from Microsoft yesterday. After I finally got the darn thing to work it makes inserting formatted HTML populated with data way easier.

After doing some searches on Google I kept finding articles that announce that Templates would be built into the version 1.5 core. I continued down the path coding by example and researching the API Docs. However I kept running into “tmpl is not a function”. After some continued research I finally found a tiny little comment made by John Resig that it in fact did not make it into the 1.5 release. So now that error makes sense.

To resolve this issue you must still load the jQuery plugin. It appears the plugin is still in beta stages and is available for download from Github or the Microsoft CDN.

Before I’ve been unable to use Microsoft’s CDN because it did not have SSL. But I went ahead and tested to see if they now have it included, and they do!

Here’s how I use it:

<script src="//ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>

This will automatically call it via http or https depending upon the current browser protocol being used.

See a related blog for jQuery on Google’s CDN here.

#cdn, #google, #jquery, #microsoft, #plugin, #template