How to show a spinner while loading an image via JavaScript

javascript

Here is an example of how you can show a spinner while loading an image using JavaScript:

// create a new image element
const imageElement = document.createElement('img');

// create a spinner element
const spinnerElement = document.createElement('div');
spinnerElement.innerHTML = 'Loading...';

// set the spinner as the content of the image element while the image is loading
imageElement.onload = () => {
  // remove the spinner once the image has finished loading
  spinnerElement.remove();
};
imageElement.onerror = () => {
  // remove the spinner if there was an error loading the image
  spinnerElement.remove();
};

// set the spinner as the content of the image element
imageElement.innerHTML = spinnerElement.outerHTML;

// set the src of the image element to start loading the image
imageElement.src = 'https://example.com/image.jpg';

// append the image element to the document
document.body.appendChild(imageElement);

This will show the spinner while the image is being loaded, and remove the spinner once the image has finished loading or if there was an error loading the image.