Skip to content

lazyLoad

The lazyLoad function takes a CSS selector, a DOM element, a list of DOM elements, or an array of DOM elements to lazy-load.

By default it matches:

img[loading="lazy"], img[loading="eager"][data-src], img[loading="eager"][data-srcset]

This means both lazy images and above-the-fold images (marked loading="eager") are processed – the eager ones just skip the viewport wait.

How It Works

  1. Eager images get the priority path. For loading="eager" images with a data-src or data-srcset:
    • data-src / data-srcset swap into src / srcset immediately.
    • fetchpriority="high" is set if no value is already present.
    • A hash placeholder is still generated when data-blurhash or data-thumbhash is present, giving you an instant placeholder while the real image fetches.
  2. Crawlers get the same immediate-swap treatment so search engines and social-preview scrapers see the real image.
  3. Lazy images get a blurry placeholder from hash-based placeholders (BlurHash / ThumbHash) if applicable, and data-sizes="auto" is expanded to a real sizes value.
  4. Viewport timing is handled by the browser via the native loading="lazy" attribute – lazy images are swapped to their real sources when the browser fetches them.
  5. During development, unlazy warns if your LCP element is configured for lazy loading. See the Core Web Vitals guide.

Options

Options can be passed to the function to customize its behavior:

OptionTypeDefaultDescription
hashboolean | stringtrueWhether to use a hash for generating a blurry placeholder. Can be true (auto-detect from data-blurhash/data-thumbhash), false (disabled), or a hash string.
hashType'blurhash' | 'thumbhash''blurhash'The type of hash to use. Ignored when hash is boolean (auto-detected from data attributes).
placeholderSizenumber32The size of the longer edge for BlurHash decoding. Ignored for ThumbHash.
updateSizesOnResizebooleanfalseWhether to update the sizes attribute on resize events using a debounced ResizeObserver. Useful for responsive layouts where image display size changes.
onImageLoad(image: HTMLImageElement) => void-Callback invoked when an image loads successfully.
onImageError(image: HTMLImageElement, error: Event) => void-Callback invoked when an image fails to load.

Return Value

The function returns a cleanup function that removes all event listeners and ResizeObservers created by lazyLoad. Call this function when images are no longer needed to prevent memory leaks:

ts
const cleanup = lazyLoad()

// Later, when cleaning up
cleanup()

Type Declarations

ts
export interface UnLazyLoadOptions {
  /**
   * Whether to generate a blurry placeholder from a [BlurHash](https://blurha.sh)
   * or [ThumbHash](https://github.com/evanw/thumbhash) string. The placeholder
   * image will be inlined as a data URI in the `src` attribute.
   *
   * @remarks
   * If this option is set to `true`, the `data-blurhash` or `data-thumbhash`
   * attributes will be used for the hash string. If you pass a single element
   * as the `selectorsOrElements` argument, you can also pass a string to this
   * option to override the hash string.
   */
  hash?: string | boolean

  /**
   * Specify the hash type to use for generating the blurry placeholder.
   *
   * @remarks
   * This option is ignored if the `hash` option is set to a boolean value.
   * In these cases, the `data-blurhash` or `data-thumbhash` attributes will
   * be used to determine the hash type.
   *
   * @default 'blurhash'
   */
  hashType?: 'blurhash' | 'thumbhash'

  /**
   * The size of the longer edge (width or height) of the BlurHash image to be
   * decoded, depending on the aspect ratio.
   *
   * @remarks
   * This option is ignored if the `hashType` option is set to `thumbhash`.
   *
   * @default 32
   */
  placeholderSize?: number

  /**
   * Whether to update the `sizes` attribute on resize events with the current image width.
   *
   * @default false
   */
  updateSizesOnResize?: boolean

  /**
   * A callback function to run when an image is loaded.
   */
  onImageLoad?: (image: HTMLImageElement) => void

  /**
   * A callback function to run when an image fails to load.
   */
  onImageError?: (image: HTMLImageElement, error: Event) => void
}
ts
export function lazyLoad<T extends HTMLImageElement>(
  /**
   * A CSS selector, a DOM element, a list of DOM elements, or an array of DOM elements to lazy-load.
   *
   * @default 'img[loading="lazy"], img[loading="eager"][data-src], img[loading="eager"][data-srcset]'
   */
  selectorsOrElements?: string | T | NodeListOf<T> | T[],
  options?: UnLazyLoadOptions,
): () => void

Released under the MIT License.