Image loading asynchrony in JavaScript

Images that are dynamically created via JavaScript are also loaded asynchronously. Consider for example the following code:

let image = document.createElement('img'); image.src = 'img.png'; document.body.appendChild(image);

As you can see, here we create the img tag, write the path to the image in its src and place this image in body. The image, however, will not appear on the page immediately. The fact is that when we wrote down the path to the image into src, the browser starts downloading this image from the site. As soon as the image is downloaded, only then the browser will be able to show it.

If the image is large enough, and the Internet speed is low enough, then the site user will be able to "admire" an empty image for some time - until it is downloaded.

In fact, the img tag has an load event that fires when the image is downloaded:

let image = document.createElement('img'); image.src = 'img.png'; image.addEventListener('load', function() { // will fire after the image download });

We can use this to append an image on a page only when that image is downloaded:

let image = document.createElement('img'); image.src = 'img.png'; image.addEventListener('load', function() { document.body.appendChild(image); // we append it after download });

The image will not necessarily load: it may be that a path to the image is incorrect, or the Internet will break, the server with the site will break, or something similar. In other words - an exception will occur. In this case, not the load event will work, but the error event:

let image = document.createElement('img'); image.src = 'img.png'; image.addEventListener('load', function() { document.body.appendChild(image); }); image.addEventListener('error', function() { // an image loading error });

Create a button that will download an image when clicked. Show the image when it is loaded. Display a message if there are problems with the image download.

enru