Monday, April 6, 2009

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.

29 comments:

  1. Great tip,
    Small addition though:
    Using the ajaxStart and $.ajaxComplete is great for a generic loading experience, whenever an ajax call is done from your page.
    Furthermore, using the blockUI plugin to block the updating element is also recommended.

    Cheers,
    Erik

    ReplyDelete
  2. This kind of "tip", in my opinion, would not deserve an article... anyone ignoring such basic things,... should event not try to make anything using AJAX...

    ReplyDelete
  3. It is better to load that image at the begining, and put display:none in css, and than use .show() and .hide() when you need it.

    ReplyDelete
  4. @Anonymous1, Well it depends how you look at it. Some jQuery newbies know about all the jQuery functionality but can not put it all together. And this post might help them. I wrote the post analysing my Google Analytics logs, so there must be some who found this article useful.

    @Anonymous2, Yes, I agree, that would preload the image and users would see it right away.

    Thanks for your comments, they are appreciated.

    ReplyDelete
  5. I'm using this solution to display and hide the loader:

    $().ajaxSend( function( r, s ) {
    $("#ajaxloader").show();
    });
    $().ajaxStop( function( r, s ) {
    $("#ajaxloader").fadeOut();
    });

    And I don't need any event to display when AJAX data is coming :)

    ReplyDelete
  6. One could bind custom functions to jquery's ajax events, and so implement an automatic ajax hide and show in the following way:

    $("#ajax_loading_div")
    .bind("ajaxSend", function(){
    $(this).show();
    })
    .bind("ajaxComplete", function(){
    $(this).hide();
    });

    ReplyDelete
  7. The guy who created this article is, in my humble opinion, a much better person than anyone one of you who posted below. Sure its easy to look at someone else's work and critique it. But I don't see any of you who mocked him with enough balls to put your neck out on a limb in an attempt to help others learn.

    ReplyDelete
  8. :) I, for one, am appreciative of articles such as this one that try and help people even if only in the little things.
    Tim, most ppl who commented aren't criticizing (nevermind mocking!) the author, they are just suggesting improvements to help others who might read this post.

    ReplyDelete
  9. kinda new with ajax implimentation, is this example usable for file upload?

    wondering if there is working demo for this example, i couldnt' get it to work.

    ReplyDelete
  10. Please post a working demo.

    thanks

    ReplyDelete
  11. Uzbekjon:

    I'm a jquery noob (understatement). Is it possible to use this to display an animated gif while a page is loading? I have a webpage that uses jquery and "cycle" to load and rotate a bunch of logo graphics. It is slow to load and I need a way to display a loading indicator until it is ready.

    Thanks!

    ReplyDelete
  12. Pity, no demo :·((

    ReplyDelete
  13. Geez, you just saved my life. Building my new website, this info was just what I've been looking for to greate a "non-page-refreshing" news block using jquery and it's ajax implementation.

    Now that I've got the loader working too, there's nothing stopping me anymore. Thank you so much for this article!

    ReplyDelete
  14. This is repaired version :

    $("#btnLoad")
    $("#content")
    $("#content")

    instead

    $("btnLoad")
    $("content")
    $("content")

    The selector # there is a missing

    ReplyDelete
  15. I'm using just plugin =)
    http://plugins.jquery.com/plugin-tags/ajaxloader

    ReplyDelete
  16. Waon thnkx simple easy affective!

    ReplyDelete
  17. It might be easier to simply use a jQuery plugin to give you more options, i.e. Spinner.

    http://www.jqueryin.com/projects/spinner-jquery-preloader-plugin/

    ReplyDelete
  18. if i have a list image, how to make loading image frst, before each image load done.

    Exp:

    image src="1.jpg"
    image src="2.jpg"
    image src="3.jpg"

    How to make image loading first for each image?

    ReplyDelete
  19. I was wondering if there are any loading apng generators. Does anyone know good ones?

    ReplyDelete
  20. Muy buen Post! Gracias

    ReplyDelete
  21. Please can you share a demo files to us ? thanks

    ReplyDelete
  22. it’s a nice and good tutorial…
    well done… :)

    ReplyDelete
  23. A full working example would be nice for those who don't know wtf is going on... Thanks

    ReplyDelete