jQuery Ajax Loading Image
Show a centred loading image while Ajax calls run, then reveal the page when they finish.
When a page fills its controls through Ajax, users see empty fields until the data arrives. A loading image fixes that: show it first, hide the form, and swap them once all Ajax calls finish.
Step 1: the loader
A div that holds the loading image:
html
<div id="loader">
<img src="/images/ajax-loader.gif" class="centeredImage" />
</div>
CSS to centre it:
css
.centeredImage {
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -150px;
}
Step 2: hide the page content
Wrap the page elements in a div and hide it by default:
html
<div id="mainDiv" style="display:none;">
<!-- All form elements go here -->
</div>
Step 3: the script
js
$(function () {
$(document).ajaxStart(function () {
// Nothing to do here: mainDiv is hidden
// and the loader is already displayed
});
$(document).ajaxStop(function () {
$('#mainDiv').show();
$('#loader').hide();
});
});
ajaxStop fires when all running Ajax requests have completed, so the form appears only once the data is ready.