Skip to content

Responsive Lazy Backgrounds

The v-lazy-img directive lazy-loads a background but can't do srcset. useBackgroundImage() is the composable counterpart: lazy loading + responsive image-set() (the CSS-native equivalent of srcset) + blur-up — returned as a reactive :style you bind yourself.

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

const { target, style, isLoaded } = useBackgroundImage('/hero.jpg', {
  placeholder: 'data:image/jpeg;base64,/9j/...',
  densities: [1, 2], // → image-set(url("/hero.jpg") 1x, url("/hero.jpg") 2x)
  rootMargin: '300px',
})
</script>

<template>
  <section ref="target" :style="style" class="hero">
    <h1 v-show="isLoaded">Welcome</h1>
  </section>
</template>

<style scoped>
.hero {
  width: 100%;
  height: 60vh;
}
</style>

Options

placeholder

string, optional. URL/data URL shown (blurred) until the full image loads.

densities

number[], optional. Builds a responsive image-set() with 1x/2x/… entries.

type

string, optional. MIME hint for image-set() entries (e.g. 'image/webp').

lazy

boolean · default: true. Gate loading behind IntersectionObserver.

rootMargin

string · default: '200px'. IO root margin.

threshold

number · default: 0. IO threshold.

transition

string · default: '0.4s ease'. Blur-up transition.

backgroundSize

string · default: 'cover'. background-size.

backgroundPosition

string · default: 'center'. background-position.

Return value

{ target, style, status, isLoaded, isLoading, load }. Attach target via a template ref and bind style; call load() to trigger manually when lazy: false. SSR-safe (loading is deferred to the client).