Skip to content

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 ​

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:

  1. The component should wrap a native <img> element with the loading="lazy" attribute set.
  2. The component should support at least a src or srcset attribute.
  3. Import the lazyLoad function from the unlazy library and call it with the HTMLImageElement as the first argument:
ts
import { lazyLoad } from 'unlazy'

lazyLoad(target)
  1. 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)
})

Released under the MIT License.