Home / Loading content with jQuery AJAX – using a loading image

Loading content with jQuery AJAX – using a loading image

A couple of weeks back I looked at how to load remote content with jQuery and AJAX using the jQuery .load() function. This post expands the functionality by looking at how to put a loading image as a placeholder where the new content will go while it is still downloading.

The .load() function doesn’t have any way of dealing with errors in the examples provided here, so if the content is never loaded then the loading image will continue to display. I will show how to allow for error handling in a future post.

I get my loading images from www.ajaxload.info which is a useful resource for generating animated GIF images suitable for showing content is loading. There are a number of different indicator images and you can change the foreground and background colours.

Example in action

Click the "Click Me!" button below to see a working example in action. If you are viewing this in an RSS reader then you’ll need to click through to the post in a web browser for the example to work.

After clicking "Click Me!" the loading image will appear, then the AJAX request will be made. The content from the AJAX request will replace the loading image once it has been loaded. For the purposes of this example, there’s a 2 second delay between the loading image displaying and the AJAX request being made. See my "Using setTimeout() with Javascript" post for details about how to make a function run after a set time.

Placeholding text

How it works

The HTML for the above example looks like this:

<input type="button" onclick="example_ajax_request()" value="Click Me!" />
<div id="example-placeholder">
  <p>Placeholding text</p>

The Javascript for the example looks like this (ignoring the call to setTimeout):

function example_ajax_request() {
  $('#example-placeholder').html('<p><img src="/images/ajax-loader.gif" width="220" height="19" /></p>');

The first line in the example_ajax_request() function sets the html of the <div> to the loading image, and the second line then loads the content from /examples/ajax-loaded.html into the div.

It’s best in this sort of situation to pre-load the loading image so that when the button is clicked it appears immediately from the cache. If this is not done then the AJAX request may be completed before the image has finished downloading. I’ll look at doing that in another post.

Future posts

The next two posts in this jQuery AJAX content loading series will look at how to load the remote content but deal with errors, and then how to preload the loading image.