I’m building a website that shows data graphs as PNG files. When users click different buttons, I want to swap out the current graph without reloading the whole page.
Right now I’m using this JavaScript code to change the image:
The issue is there’s a delay of several seconds while the new graph loads. Users don’t get any feedback during this time and think nothing happened when they clicked.
I need to show a loading animation or progress indicator while the new image downloads. I tried using a simple timeout to show a spinner temporarily, but that doesn’t work well since load times vary.
Someone suggested using the lowsrc attribute like this:
But my loading spinner is much smaller than the actual graphs, so it looks weird.
What’s the best way to handle this? I want users to see immediate feedback when they click, then have the spinner disappear once the new graph finishes loading.
Had this exact problem last year building a dashboard with dynamic charts. Best solution I found was preloading the image in JavaScript, then swapping it once it’s loaded. Create a new Image object, set up an onload handler, and only update your actual img src after the new image downloads. Show your loading spinner over the existing image with CSS positioning while it preloads. This worked well for me: javascript const loader = new Image(); loader.onload = function() { document.querySelector('#graph-container').src = this.src; hideLoadingSpinner(); }; showLoadingSpinner(); loader.src = '/data/chart-5.png'; Users get instant feedback when they click, spinner shows for the actual load time, and no awkward size issues since you’re overlaying the spinner instead of replacing the image.
i use placeholder divs with CSS bg images instead. set up two containers - one shows the spinner while the other loads the new graph behind it. when it’s ready, just toggle visibility with a fade effect. way simpler than dealing with preload stuff.
I had a similar issue with an analytics portal where users generated different report visualizations. Here’s what worked for me: I used opacity transitions with absolute positioning for smooth loading. Wrap your image container in a relative-positioned div, then position your loading indicator absolutely on top. When someone clicks to load a new graph, I immediately fade the current image to 50% opacity and show the spinner centered over it. Once the new image preloads via JavaScript, I swap the source and fade back to full opacity. Users get clear feedback that something’s happening, plus the layout stays intact since the original image remains in place. Pro tip: give your loading indicator a semi-transparent background so it pops against any underlying graph content.