Loading States During Preview Generation
You'll learn how to show users visual feedback while FileReader asynchronously converts large images into preview-ready data URLs.
Why Loading States Matter
When you call readAsDataURL() on a large image file, the browser doesn't freeze—it processes the file asynchronously. For small files this happens almost instantly, but large photos (think multi-megabyte smartphone images) can take noticeable time. Without feedback, users may wonder if their upload worked or if the app is broken.
Think of it like a microwave: you don't just stare at a silent box hoping your food is heating. You see the light, hear the hum, and watch the timer count down. Loading indicators serve the same purpose during file processing.
The Pattern
Since FileReader uses event-driven callbacks, you sandwich your loading indicator between the start of the read operation and the load or error events:
- Show a loading spinner or message when you call
readAsDataURL() - Hide it when the
loadevent fires (success) orerrorevent fires (failure)
The gap between these moments is when the async work happens—especially noticeable with large files.
const reader = new FileReader();
const loadingEl = document.getElementById('loading-spinner');
// Show loading state
loadingEl.style.display = 'block';
reader.onload = (e) => {
// Hide loading, show preview
loadingEl.style.display = 'none';
previewImg.src = e.target.result;
};
reader.onerror = () => {
loadingEl.style.display = 'none';
alert('Preview failed');
};
reader.readAsDataURL(imageFile);
Key Takeaway: Always display loading indicators before calling readAsDataURL() and hide them in both the load and error handlers to give users clear feedback during asynchronous file processing.