Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

js load multiple images

// Array of images to load.
const images = [
	"path/to/image.extension",
	"/images/someimage.png",
	"./images/anotherimage.jpg",
	"../separatefolder/assets/onelastimage.gif"
];

// Function to load an image.
function loadImage(src) {
	return new Promise(function(res, rej) {
		const image = new Image();
		function loadCallback() {
			image.removeEventListener("load", loadCallback);
			image.removeEventListener("error", errorCallback);
			res(image);
		}
		function errorCallback() {
			image.removeEventListener("load", loadCallback);
			image.removeEventListener("error", errorCallback);
			rej(image);
		}
		image.addEventListener("load", loadCallback);
		image.addEventListener("error", errorCallback);
		image.src = src;
	});
}

// Function to load multiple images.
function loadImages(...srcs) {
	const promises = [];
	for (let i = 0; i < srcs.length; i++) {
		promises.push(loadImage(srcs[i]));
	}
	return Promise.all(promises);
}

// Load the images in the images array and print them to the console.
loadImages(...images).then(console.log);
 
PREVIOUS NEXT
Tagged: #js #load #multiple #images
ADD COMMENT
Topic
Name
5+9 =