Keep the current gallery image visible until its replacement is ready to display. Waiting for image decoding before committing a swap can prevent an empty frame, but the replacement must still match the visitor's latest selection.
Separate fetching, decoding and presentation
A gallery can receive the correct file and still show an awkward transition. Downloading supplies compressed image data. Decoding prepares that data for display, while the component decides when to replace the visible element. Treat those as separate stages when investigating a flash, a missing frame or a photograph that appears after its caption.
The browser's HTMLImageElement.decode() promise provides a readiness boundary for a dynamically created image. Set its source, await decoding, then insert that same prepared element. This does not make the network faster or guarantee that the next screen refresh occurs immediately. It gives your component a point at which to make a deliberate presentation decision instead of removing useful content while preparation is still unfinished.
Read the HTML Standard's image decoding contract when defining that boundary. The practical workflow below concerns an interactive gallery with an already visible image. It is not a reason to hide the initial page image behind JavaScript or to delay discovery of content that belongs in the original document.
Define the visible state before writing the loader
Give each gallery instance its own selected item, currently displayed item and pending request identity. Those values can differ during loading. If someone selects photograph B while photograph A remains on screen, the interface should communicate that B is loading without claiming that A is B. Keep the existing caption attached to the displayed photograph until the replacement is committed.
Reserve a stable display area. An image swap should not unexpectedly move the next button or the text the visitor is reading. Choose a consistent frame ratio where the design allows it, and decide whether differently shaped photographs are contained or cropped. This is a product decision, not something a decoding promise can solve. Check portrait and landscape examples before adopting one rule everywhere.
Also decide how failure looks. The existing image can remain useful while a compact message explains that the requested photograph could not load. Provide a retry action and keep navigation available. Avoid clearing the gallery at selection time: doing so removes the very fallback that would make a slow connection or broken file tolerable.
Prepare one replacement without mutating the live image
Create a separate image object for the candidate. Set its meaningful alternative text and the sizing attributes needed by your layout, then provide its source. Await its decoding promise without changing the source midway through preparation. On success, verify that the request is still current and replace the displayed element with the prepared candidate. Update its caption and displayed-item record in the same commit.
Using a separate candidate keeps preparation away from the visible image. Repeatedly assigning new sources to the live element makes it harder to preserve the previous photograph and to explain which request a completion belongs to. The candidate object also gives tests a concrete object to inspect: its chosen resource, dimensions, description and associated item must all agree before it reaches the frame.
Do not confuse the decoding attribute with this control flow. It expresses a decoding preference; it is not a promise that your application can await. Similarly, a finished download is not your application-level permission to overwrite the current selection. The important transition is from a prepared candidate to an explicitly accepted visible result, with a final identity check immediately before committing it.
Prevent older requests from winning a race
Suppose a visitor selects B and then C. C may finish first because its file is smaller or already cached. Without a request identity check, B can finish later and replace C, making the gallery appear to ignore the latest click. Network completion order must not become selection order.
Use a monotonically increasing counter per gallery. Increment it for each selection and capture the value when preparation begins. After awaiting decoding, compare the captured value with the latest counter. If they differ, discard the candidate without touching the frame, caption or current error message. Apply the same check in the failure path: a rejected older request should not show an error over a newer successful image.
When the component is removed or a route changes, invalidate its pending identity as well. A late completion should not recreate content in a detached gallery or update a new instance. This guards presentation; it does not necessarily cancel the underlying download. Keep that distinction explicit when measuring network traffic, and avoid promising bandwidth savings from a stale-result check alone.
| Situation | Visible result | Required decision |
|---|---|---|
| Current candidate finishes | Replace image and caption together | Confirm identity immediately before commit |
| Older candidate finishes | Keep the latest accepted image | Discard the stale result |
| Current candidate fails | Keep the previous image and offer retry | Show an error for the current selection |
| Older candidate fails | Leave the current interface unchanged | Ignore the stale failure |
| Gallery is removed | Do not update the former frame | Invalidate pending work |
Keep responsive selection and layout consistent
A responsive gallery needs more than an appropriate file extension. Its candidate-selection information should match the size at which the image will be displayed. If you use srcset and sizes, configure them consistently with the visible component and inspect the selected resource. A prepared image that downloads a much larger candidate than necessary can make a smooth transition expensive.
Complex art direction needs particular care. A detached standalone image does not automatically reproduce the source selection of an existing picture container. Do not prepare one resource and assume that inserting it into a different selection context will preserve that choice. Test the actual container and viewport changes, or keep the replacement design simple enough that the prepared and displayed resource remain aligned.
Use the image optimization guide to review file sizing and responsive delivery separately from swap logic. Record the selected resource and rendered dimensions in your test notes. A successful decode says that one request became usable; it does not certify that the design chose an efficient resolution, a suitable crop or the correct photograph for the current item.
Handle errors without endless retries or misleading content
Treat preparation failures as an expected state. An unavailable resource, invalid image data or a changed request can prevent successful decoding. Catch the rejection, check whether it still belongs to the current selection, and retain the last accepted image. Log enough context to diagnose the item and stage while avoiding visitor-specific information in diagnostic URLs.
A retry should create a new request identity. This prevents the failed attempt from retaining authority over the new attempt's status. Do not automatically retry in an unbounded loop: a permanently broken resource will keep consuming work without helping the visitor. A limited explicit retry also makes it easier to distinguish an intermittent connection problem from incorrect gallery data.
Keep alternative text and captions truthful throughout the process. Announce a concise loading or failure state through the component's established accessible status pattern, but avoid moving keyboard focus to every new photograph. Test keyboard navigation while requests are pending. A visually polished transition is still broken if the controls lose focus or the spoken description refers to a different item.
Bound preparation instead of decoding the whole gallery
Preparing every photograph in advance can exchange a visible delay for unnecessary downloads and memory pressure. Start with the image the visitor actually requests. If evidence supports preparing a likely adjacent image, set a small, explicit limit and discard references to candidates that are no longer useful. Do not describe an arbitrary preload count as a browser requirement.
Account for rapid navigation. Several outstanding candidates can exist even when only the latest may be displayed. The identity guard protects correctness, while a separate preparation policy controls how much work you initiate. Consider whether repeated selections can reuse the same in-flight preparation, and ensure that reuse does not bypass the latest-selection check when the result returns.
A cache hit does not remove the need for testing. Warm browsing can conceal the waiting state that appears on a first visit, while a large gallery session can reveal costs that a two-image demonstration misses. Test the beginning, middle and end of a realistic browsing sequence, including returning to an image and leaving the gallery before preparation finishes.
Verify the transition as a complete user journey
Record a baseline and the modified gallery under matching conditions. Capture the visible sequence alongside network activity and a performance trace. Look for the existing image remaining visible during preparation, one accepted commit for the latest selection, and no extra work caused by duplicate handlers. Compare a cold load with a warm repeat rather than mixing them into one conclusion.
Include slow delivery, a missing resource, corrupted image data, rapid forward-and-back navigation, viewport resizing and component removal in the test matrix. Check caption correctness, reserved geometry and keyboard focus in each case. These are acceptance conditions for the feature, not just optional edge cases to examine after a speed score improves.
Report what the change actually achieved. A gallery may eliminate empty frames while total download time remains unchanged. It may also expose an oversized candidate that needs separate correction. Keep the readiness gate, selection guard and delivery policy independently understandable so the next maintenance change preserves both responsiveness and the visitor's intended photograph.