It is simple to load images to the page using JavaScript. We can create it using two methods then append it to the DOM.
var img1 = document.createElement("img");
var img2 = new Image();
img1.src = "path/to/image1.jpg";
img2.src = "path/to/image2.jpg";
document.body.append(img1);
document.body.append(img2);
That was easy. Images take time to load however. If the images are very big, they won’t be loaded by the time they are added to the DOM. We can detect this event using onload.
img1.onload = function() {
console.log("Image 1 ready to append");
document.body.append(this);
};
Note that the order of your code does matter. The onload function has to be defined before the src of the image is set:
img1.src = "path/to/image.jpg";
img1.onload = function() {
// this may not run
// especially if the image is small
};
img2.onload = function() {
// this will run when the image is ready
}
img2.src = "path/to/image.png";
You can also run a function when an image fails to load using the onerror event. The process is to define the function to run when the image is loaded, the function to run when the image fails to load, then you set the source path to the image.
var img = new Image();
img.onload = function() {
// the image is ready
};
img.onerror = function() {
// the image has failed
};
img.src = "path/to/image.jpg";
A good example where you can make use of those events is if you are creating a photo gallery. When you select an image, you can add a the words “Loading” while the images are loading in the background. Only when the image is loaded you show it to the user.