HTMLImageElement
Image Element
Represents an <img> tag. Use it to load images, read their natural dimensions, handle loading errors, and improve page performance with lazy loading.
<img
src="photo.jpg"
alt="Profile photo"
loading="lazy"
>
Key Properties
| Property | Type | Description |
|---|---|---|
| src | string | The image URL. Setting it starts loading the new image. |
| alt | string | Text alternative for accessibility and failed image loads. |
| width / height | number | Rendered dimensions in CSS pixels. Set both to reserve layout space. |
| naturalWidth / naturalHeight | number | The real pixel size of the loaded image. Read-only. |
| loading | string | "lazy" delays offscreen images. "eager" loads immediately. |
| complete | boolean | True when the browser has finished trying to load the image. |
Common Methods
| Method | Returns | Description |
|---|---|---|
| decode() | Promise | Waits until the image is decoded and ready to paint. |
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