Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Image `load` and `error` events

Handle image loading success and failure on the image element itself. Register both handlers before setting `src`, and do not treat `complete` as proof of success.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

const image = new Image();
image.addEventListener("load", onLoad);
image.addEventListener("error", onError);
image.src = url;

// Alternative to addEventListener():
// image.onload = onLoad;
// image.onerror = onError;

Image load/error events report what happened to an image resource. new Image() creates an HTMLImageElement, an <img> that can load without being inserted into the document. This is a browser API, not part of ECMAScript 2024. The browser fires load on the element when the resource loads successfully and error when it cannot load or use the resource, for example because the URL is unreachable or the image data is invalid. The image's error event is neither a thrown JavaScript exception nor a response containing an HTTP status.

Listen on the image itself: neither event bubbles, and neither is cancelable. Register both handlers with addEventListener() before assigning src. Alternatively, set onload and onerror; assigning to either property again replaces the handler in that property. Reading src gives you a URL, not the loading outcome or a Promise.

If an existing image has already fired an event, a new listener will not replay it. complete alone does not prove success: it can also be true for a broken image or when no source is set. For an expected image with a positive intrinsic width, image.complete && image.naturalWidth > 0 is a useful check that it is already available.

load does not mean the image has been painted. If you need to wait for decoding before inserting it into the document, use await image.decode() and handle rejection. Successfully loading a cross-origin image does not by itself let you read its pixels back from a canvas; CORS restrictions still apply.

Examples

<!doctype html>
<meta charset="utf-8">
<title>Image load and error events</title>
<script>
(async () => {
  function imageOutcome(url) {
    return new Promise((resolve) => {
      const image = new Image();
      function finish(event) {
        image.removeEventListener("load", finish);
        image.removeEventListener("error", finish);
        resolve(event.type);
      }
      image.addEventListener("load", finish);
      image.addEventListener("error", finish);
      image.src = url;
    });
  }

  const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"><rect width="1" height="1"/></svg>';
  const dataURL = (text) => `data:image/svg+xml,${encodeURIComponent(text)}`;
  console.log(await imageOutcome(dataURL(svg)));
  console.log(await imageOutcome(dataURL("not an SVG")));
})();
</script>

Result

load
error

Save the example as an `.html` file, open it in a browser that allows `data:` images on the page, and check the developer console. Without contacting an external server, the code checks a valid SVG first and then invalid image data. It uses a separate image for each attempt and removes both listeners when the outcome arrives. The expected messages are `load` and then `error`.

Related lessons

  • JavaScript · Lesson 33 · Advanced · Version: 4

Sources