Display loading GIF image while loading through AJAX

Well, let's face it, AJAX is everywhere. Nowadays clients want AJAX "enabled" web applications. They want their web sites to be Web2.0 and that is usually associated with using AJAX. No doubt using AJAX to load parts of your page and use more javascript effects, made easy by jQuery, is a great way to bring your website to life. But we should not forget about our users and the website usability. That is why it is a good practice to display something like text or image that informs users that the content is being loaded or processed.

Now, let's see how can we display a loading image while requested content is being loaded by one of the jQuery's AJAX functions. Here is what happens:

  1. Something triggers AJAX request (like "search" button click);
  2. We put the loading image or a text that ask for user patience to the place where we would later insert the loaded content (or anywhere else);
  3. After remote content is fully loaded, we remove/hide the loading image/text and insert the loaded content.

To make it more apparent, imagine we have HTML page with this markup:

<button id="btnLoad">Load Content</button>
<div id="content">
  Please click "Load Content" button to load content.
</div>

We want to load content when a user clicks on the "Load Content" button. So we need to bind a click event to that button first and make AJAX request only after it is fired.

$("#btnLoad").click(function(){
    // Make AJAX call
    $("#content").load("http://example.com");
});

The above code loads contents from http://example.com into the <div id="content">. While the page is being loaded we want to display our animated GIF image in the "content". So we could further improve our code like so:

$("#btnLoad").click(function(){

  // Put an animated GIF image insight of content
  $("#content").empty().html('<img src="loading.gif" />');

  // Make AJAX call
  $("#content").load("http://example.com");
});

The .load() function would replace our loading image indicator with the loaded content.

Final note:

You might be using jQuery’s other AJAX functions like $.ajax(), $.get(), $.post(), in this case use their callback function to remove loading image/text and append your loaded data.

If you have any question, please tweet me.