Integrations
unlazy supports lazy loading images in your framework of choice. Each package provides a UnLazyImage component as a drop-in replacement for the native <img> element.
Available Integrations
- Vue
- React
- Solid
- Svelte
- Nuxt, which also decodes hash-based placeholders (BlurHash and ThumbHash) on the server
To decode hashes on the server in another framework, see Server-Side Rendering.
UnLazySource
Every UnLazyImage component takes a sources prop. Each UnLazySource entry renders one <source> inside a <picture>:
ts
export interface UnLazySource {
/** Image source set for the `<source>` element. Will be applied lazily via `data-srcset`. */
srcSet: string
/**
* Media query that selects this source, e.g. `(max-width: 600px)`. Use this for art
* direction across breakpoints.
*/
media?: string
/** MIME type for format negotiation, e.g. `image/avif` or `image/webp`. */
type?: string
/**
* Explicit `sizes` value. When unset and the parent has automatic sizing enabled, the
* source falls back to `sizes="auto"` (resolved to a numeric pixel width).
*/
sizes?: string
/**
* Intrinsic width in pixels. When the matching `<source>` is selected, the browser uses
* this together with `height` to set the rendered `<img>`'s aspect ratio. Prevents
* layout shift when the breakpoint changes.
*/
width?: number
/** Intrinsic height in pixels. Pairs with `width` to prevent layout shift across breakpoints. */
height?: number
}Creating Custom Integrations
To create a component for your framework, keep the following in mind:
- The component should wrap a native
<img>element with theloading="lazy"attribute set. - The component should support at least a
srcorsrcsetattribute. - Import the
lazyLoadfunction from the unlazy library and call it with theHTMLImageElementas the first argument:
ts
import { lazyLoad } from 'unlazy'
lazyLoad(target)- If the component gets unmounted before the image is loaded, call the cleanup function returned by
lazyLoad. Take the following example from the Vue integration:
ts
import { lazyLoad } from 'unlazy'
import { ref, watchEffect } from 'vue'
const target = ref<HTMLImageElement | undefined>()
watchEffect((onCleanup) => {
if (!target.value)
return
const cleanup = lazyLoad(target.value)
onCleanup(cleanup)
})