Vize

use-image

Preload an image and track its loading state.

Package @vizejs/composable/use-image
Own the source vize lib pull composable:use-image
Runtime exports useImage
Gzip budget 2048 B

Minimal setup

Use a Vue 3.5+ project with Vue SFC compilation configured (see Vite+ integration).

vp install @vizejs/composable

Import the entry directly. Call lifecycle-bound utilities inside <script setup> so cleanup follows the component scope; consult the runtime contract for this entry's SSR and hydration behavior.

import { useImage } from "@vizejs/composable/use-image";

Try it

Show an avatar with a fallback

Load an image before showing it, and react to loading errors.

Open the interactive example

What to observe: The valid avatar reports Loaded 64 × 64. Choose Broken to see the fallback message.

The source can be a getter, so changing it starts a new load. status is idle, loading, loaded or error.

Compare the initial and interacted states
Show an avatar with a fallback: initial state
Initial state
Show an avatar with a fallback: state after the verified interactions
After the verified interactions

Copy the example

Save this complete SFC in your Vue project. Its public imports and source are the same ones executed in the preview.

<script setup lang="ts">
import { ref } from "vue";
import { useImage } from "@vizejs/composable/use-image";

const avatars = {
  Valid: `data:image/svg+xml,${encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64"><rect width="64" height="64" fill="#42b883"/></svg>')}`,
  Broken: "data:image/png;base64,AAAA",
};
const choice = ref<keyof typeof avatars>("Valid");
const { status, image } = useImage(() => ({ src: avatars[choice.value] }));
</script>

<template>
  <div class="composable-example">
    <p>Show a placeholder until an avatar loads, and a fallback if it fails.</p>
    <label>
      Avatar source
      <select v-model="choice">
        <option>Valid</option>
        <option>Broken</option>
      </select>
    </label>
    <img v-if="status === 'loaded'" :src="avatars[choice]" alt="Avatar" width="64" height="64" />
    <output aria-live="polite">{{
      status === "loaded"
        ? `Loaded ${(image as HTMLImageElement | undefined)?.naturalWidth} × ${(image as HTMLImageElement | undefined)?.naturalHeight}`
        : status === "error"
          ? "Could not load the avatar; showing initials instead."
          : "Loading avatar…"
    }}</output>
  </div>
</template>

Runtime contract

Utility Category Stability SSR Hydration Cleanup Targets Host globals Uses
useImage media experimental deterministic-fallback caller-managed caller, reactive-scope web, desktop window tryOnScopeDispose

API

useImage

Preload an image and track its loading state. A detached image is created for every source; the newest load wins, and superseded images have their listeners removed and their src cleared so the browser can abort the download. Use it to show a placeholder until the real image is decoded, or to validate URLs before rendering them. Server rendering: no image is created and status stays "idle". The pending load is cancelled when the owning reactive scope stops.

function useImage( source: MaybeRefOrGetter<ImageSource>, options: UseImageOptions = {}, ): ImageControls
const { ready } = useImage(() => ({ src: avatarUrl.value }));
// <img v-if="ready" :src="avatarUrl"> <Skeleton v-else />

Types

ImageSource

Image attributes accepted by useImage.

Member Type Description
src string Image URL.
srcset? string Responsive candidates.
sizes? string Responsive layout sizes.
alt? string Alternative text.
crossOrigin? "anonymous" | "use-credentials" CORS mode.
referrerPolicy? ReferrerPolicy Referrer policy.
loading? "eager" | "lazy" Loading strategy.
decoding? "sync" | "async" | "auto" Decoding hint.
fetchPriority? "high" | "low" | "auto" Fetch priority hint.
width? number Intrinsic width.
height? number Intrinsic height.

ImageLike

HTMLImageElement subset used by useImage.

Member Type Description
src string Image URL.
srcset string Responsive candidates.
sizes string Responsive layout sizes.
alt string Alternative text.
crossOrigin string | null CORS mode.
referrerPolicy string Referrer policy.
loading string Loading strategy.
decoding string Decoding hint.
fetchPriority? string Fetch priority hint; absent in engines without priority hints.
width number Intrinsic width.
height number Intrinsic height.

UseImageOptions

Options for useImage.

Member Type Description
immediate? boolean Load when created and whenever the source changes.
host? MaybeRef<ImageHost | null | undefined> Image constructor for alternate runtimes and tests. A ref (not a getter) because the host is a constructor function.

ImageControls

Reactive state and actions returned by useImage.

Member Type Description
status Readonly<Ref<ImageStatus>> Loading state of the newest load.
image Readonly<ShallowRef<ImageLike | undefined>> Most recently loaded image.
error Readonly<ShallowRef<Event | undefined>> Error event of the newest load, cleared when a load starts.
ready ComputedRef<boolean> Whether the newest load succeeded.
load () => Promise<ImageLoadResult> Load the current source, superseding any pending load.