Ajax 'Loading Indicator' Design Pattern

Almost all Ajax apps shows a small loading indicator(usually a small rotating gif image) when they are sending or receiving data from the server. It is not there for decoration - it makes the application faster in the eyes of the user. Its not real speed - its a 'perceived speed' - an assurance to the user that something is happening behind the scenes.

Anyway most people are using it. Its really simple actually...

This is the pattern I use...

loading();
JSL.ajax("delete.php?id=15&ajax=1").load(function(data) {
	loaded();
	if(data.success) removeTask(data.id);

},'json');

I like the simplicity of this approach - it just has two functions - loading() and loaded(). The code for those functions are simple as well...

function loading() {
	$("loading").show(); //or document.getElementById("loading").style.display = "block";
}
function loaded() {
	$("loading").hide();//or, you know, display = "none"
}

The loading element look like this...

<div id="loading">loading...</div>

The CSS for element...

#loading {
	position:absolute;
	top:0;left:0; /*This may prevent it from being seen if the user has scrolled down */
	color:#fff;
	padding:2px 2px 2px 20px;
	background:red url(../images/loading-indicator.gif) no-repeat 2px;
	display:none;
}

An example of this can be seen in the Hyperlink 2.0 - Ajax Page Transitions page. Just click on any link and look at the top right corner. Its not the exact code I provided above - but it will be an example of how the indicator works.

Library Handled Indicators

Another approach is to let the ajax library handle the loading indicator. Those who looked at the top code might have seen a problem with it. If the ajax called somehow failed, the loaded() function will never be called. If the library is handling the indicator display, this problem can be avoided.

In jQuery this can be done using ajaxStart and ajaxComplete functions. To See an example, see page Simple global Ajax activity indicator with jQuery.

For YUI users, the Loading Panel Script will make this possible.

Prototype - I am not going into details here - the post Ajax Activity Indicators - Make Them Global and Unobtrusive gives is very detailed post on this topic.

JSL does this using the very powerful bind() function in JSL.ajax...

JSL.ajax('data.php?fetch=true&num=42&name=marvin').bind({
	"onSuccess":alert,
	"loading_indicator":"loading" //ID of the indicator element
});

The first argument in the bind function is an associative array which may have these options...

loading_indicator
The id of the loading indicator. This will be set to display:block when the url is loading and to display:none when the data has finished loading.
loading_text
HTML that would be inserted into the document once the url starts loading and removed when the data has finished loading. This will be inserted into a div with class name 'loading-indicator' and will be placed at 'top:0px;left:0px;'
blog comments powered by Disqus