Skip to content

Preloading Images

useImagePreloader() preloads a batch of images before navigation — useful for galleries and carousels, where you want the next slide already cached by the time the user gets to it.

vue
<script setup lang="ts">
import { useImagePreloader } from '@macrulez/vue-image-kit'

const { preload, progress, isComplete, errors } = useImagePreloader()

async function goToNextSlide() {
  await preload(['/slide-2.jpg', '/slide-3.jpg'])
  // All images are cached — transition is instant
  currentSlide.value++
}
</script>

<template>
  <div v-if="!isComplete">Loading {{ progress }}%…</div>
</template>

Return value

preload

(urls: string[]) => Promise<void>. Kicks off loading every URL in the array in parallel; resolves once every one has either loaded or failed (never rejects — a failed URL is recorded in errors instead). Calling it again resets loaded/errors and starts a new batch.

loaded

Ref<number>. Count of URLs that have settled (loaded or errored) in the current batch.

total

ComputedRef<number>. Size of the current batch.

progress

ComputedRef<number>. 0100, Math.round((loaded / total) * 100).

isComplete

ComputedRef<boolean>. true once every URL in the batch has settled.

errors

Ref<string[]>. URLs that failed to load, in the order they failed.

Network-aware by default

preload() silently does nothing (resolves immediately, no requests sent) when the user's connection has saveData enabled — preloading trades bandwidth for a smoother later transition, which is the wrong trade once the user has explicitly asked their browser/OS to save data. There's no option to override this; it isn't exposed as a parameter you can pass.