Key Properties
PropertyTypeDescription
src string The image URL. Setting it starts loading the new image. ▾
JS
const img = document.querySelector('img');
img.src = 'avatar.png';

img.addEventListener('load', () => {
  console.log('Image loaded');
});
alt string Text alternative for accessibility and failed image loads. ▾
JS
img.alt = 'Portrait of Ada Lovelace';
width / height number Rendered dimensions in CSS pixels. Set both to reserve layout space. ▾
JS
img.width = 320;
img.height = 180;
naturalWidth / naturalHeight number The real pixel size of the loaded image. Read-only. ▾

These are 0 until the image metadata is available.

JS
img.addEventListener('load', () => {
  console.log(img.naturalWidth, img.naturalHeight);
});
loading string "lazy" delays offscreen images. "eager" loads immediately. ▾
JS
img.loading = 'lazy';
img.decoding = 'async';
complete boolean True when the browser has finished trying to load the image. ▾
JS
if (img.complete) {
  console.log('Already loaded or failed');
}
Common Methods
MethodReturnsDescription
decode() Promise Waits until the image is decoded and ready to paint. ▾

Useful when you want to swap images without showing a half-loaded state.

JS
async function swapImage(url) {
  const next = new Image();
  next.src = url;
  await next.decode();

  document.querySelector('.preview').replaceChildren(next);
}

swapImage('large-photo.jpg');
Quick Examples
JS
const img = document.querySelector('img');

// Show fallback UI if the image cannot load
img.addEventListener('error', () => {
  img.alt = 'Image failed to load';
  img.src = 'fallback.png';
});

// Preload before displaying
async function loadPreview(url) {
  const preview = new Image();
  preview.src = url;
  preview.alt = 'Preview image';
  preview.loading = 'eager';
  await preview.decode();
  document.querySelector('#preview').replaceChildren(preview);
}
Related Elements
Related Properties
Related Methods