How can I display a loading spinner while an image is being fetched using JavaScript?

I am developing a web application that features a page showing a single chart represented as a .png image. There are several links on this page that, when clicked, refresh the entire content while replacing only the middle chart. My goal is to enhance performance by avoiding a full page reload since it’s about 100kb in size. Currently, I am updating the image source through JavaScript with this code:

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

The issue arises when the user clicks a link; there can be a noticeable delay before the chart updates, which may lead them to believe their action was unregistered or that the application is slow. I want to implement a spinner or some sort of loading indicator where the image resides during this delay, signifying to users that their request is being processed. I’ve explored various options, including using a pseudo timeout for the spinner but found it unsatisfactory. One device I came across was this:


However, the issue is that the spinner appears much smaller than the chart. Do you have any additional suggestions for achieving this?

You can achieve this using JavaScript to show a spinner while the image is being fetched:

  1. Add a spinner HTML element that’s initially hidden:
<div id="spinner" style="display:none;">Loading...</div>
<img id="chart" src="" alt="chart">
  1. Use JavaScript to toggle the spinner visibility and update the image:
const chart = document.getElementById('chart');
const spinner = document.getElementById('spinner');

function updateChart(url) {
    spinner.style.display = 'block';
    chart.style.display = 'none';
    const img = new Image();
    img.onload = function() {
        chart.src = url;
        spinner.style.display = 'none';
        chart.style.display = 'block';
    };
    img.src = url;
}

updateChart('/charts/10.png');

This code will show the spinner while the image is loading, then hide it once the image is ready. Adjust the spinner’s CSS to match the size of your chart.