The list of images to preload.
A promise that resolves to an array of images that were successfully preloaded.
preloadImages(["https://example.com/image.jpg"]);
// Returns a promise that resolves to an array of results.
export async function preloadImages(images: string[]): Promise<string[]> {
const results = await Promise.allSettled(
images.map((image) => {
return new Promise<string>((resolve, reject) => {
const img = new Image();
img.src = image;
// Resolve with the URL string instead of the Event object
img.onload = () => resolve(image);
img.onerror = (e: unknown) =>
reject(
new Error(`Failed to load: ${image}: ${e instanceof Error ? e.message : String(e)}`),
);
});
}),
);
// Filter out failures and map to just the successful string values
return results
.filter((result): result is PromiseFulfilledResult<string> => result.status === 'fulfilled')
.map((result) => result.value);
}
Preloads a list of images and returns a promise that resolves to an array of results.