Load Image programatically with Promise

Image can be loading either in a standard way via setting the src property on the Image tag, or you can do it programatically. If you do it programatically, you can enhance the image loading with some magic, eg show a animated CSS placeholder while the image is being loaded. Or you can try several URLs.

It may come handy. At least for my future self 🙂

export function loadImage(url: string): Promise<HTMLImageElement> {
	const promise: Promise<HTMLImageElement> = new Promise((resolve, reject) => {
		const image = new Image();
		
		image.addEventListener('load', () => {
			resolve(image);
		});

		image.addEventListener('error', (err) => reject(err));

		image.src = url;
	});

	return promise;
}

And yes, you can even load image from multiple URLs. It was one exotic use case when I needed that. Long story about unreliable legacy software …

/** 
* Try to load image from array imageUrls
* The function returns the first succesfull attempt
*/
export async function loadImageWithFallbackUrl(imageUrls: string[]): Promise<HTMLImageElement> {
	let imageEl: HTMLImageElement = undefined;

	// Cant use forEach loop here
	for (let i = 0; i < imageUrls.length; i++) {
		const imageUrl = imageUrls[i];

		if (imageEl) {
			// Image has already loaded
			continue;
		}

		try {
			imageEl = await loadImage(imageUrl);
		} catch {
			imageEl = undefined;
			continue;
		}
	}

	const message = imageEl ? 'Image has loaded' : 'Image was not found on any URL: ' + imageUrls;
	console.log(message);

	return imageEl;
}

No, this image is not relevant. It is a bonus for your eyes.