Problem

How could this code be improved?

document.getElementById("thumbnail").addEventListener("click", () => {
  const img = new Image();
  img.src = "path_to_high_res_image.jpg";
  document.getElementById("gallery").appendChild(img);

  img.onload = async () => {
    const metadata = await fetch("path_to_metadata_API").then((res) =>
      res.json()
    );
    document.getElementById("metadata").innerText = metadata.description;
  };
});
Solution

Whenever you ask “how could this code be improved?”, you open the (email) floodgate. But…

One way is that instead of waiting for the image to load before fetching the metadata, we can start fetching the metadata immediately by moving the fetch call outside of the onload handler. This will allow the metadata to load in parallel with the image.

document.getElementById("thumbnail").addEventListener("click", () => {
  const metadataPromise = fetch("path_to_metadata_API").then((res) =>
    res.json()
  );

  const img = new Image();
  img.src = "path_to_high_res_image.jpg";
  document.getElementById("gallery").appendChild(img);

  img.onload = async () => {
    const metadata = await metadataPromise;
    document.getElementById("metadata").innerText = metadata.description;
  };
});