How to detect when the images are loaded

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";


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");

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.

Do you use these events for something else? Feel free to share it.


Sam :

Is this still relevant with ES6?

ibrahim :

@Sam Yes, you can still make use of it. In fact, the same method should work in future browsers as long as we use the image tag for images.

Anonymous :

Hey, thanks for this tutorial. It works perfectly.

Ibrahim :

@Anonymous You are welcome, I'm glad it helped you.

Kingsam Perry Andrew :

Nice article. And great to find it at the top of Google search. +1 for explanation on the order of the codes.👍

Let's hear your thoughts

For my eyes only