Javascript – How to show a spinner while loading an image via JavaScript


I'm currently working on a web application which has a page which displays a single chart (a .png image). On another part of this page there are a set of links which, when clicked, the entire page reloads and looks exactly the same as before except for the chart in the middle of the page.

What I want to do is when a link is clicked on a page just the chart on the page is changed. This will speed things up tremendously as the page is roughly 100kb large, and don't really want to reload the entire page just to display this.

I've been doing this via JavaScript, which works so far, using the following code

document.getElementById('chart').src = '/charts/10.png';

The problem is that when the user clicks on the link, it may take a couple of seconds before the chart changes. This makes the user think that their click hasn't done anything, or that the system is slow to respond.

What I want to happen is display a spinner / throbber / status indicator, in place of where the image is while it is loading, so when the user clicks the link they know at least the system has taken their input and is doing something about it.

I've tried a few suggestions, even using a psudo time out to show a spinner, and then flick back to the image.

A good suggestion I've had is to use the following

<img src="/charts/10.png" lowsrc="/spinner.gif"/>

Which would be ideal, except the spinner is significantly smaller than the chart which is being displayed.

Any other ideas?

Best Solution

I've used something like this to preload an image and then automatically call back to my javascript when the image is finished loading. You want to check complete before you setup the callback because the image may already be cached and it may not call your callback.

function PreloadImage(imgSrc, callback){
  var objImagePreloader = new Image();

  objImagePreloader.src = imgSrc;
    objImagePreloader.onload = function() {
      //    clear onLoad, IE behaves irratically with animated gifs otherwise