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[data-src], img[data-srcset]

An image marked loading="lazy" loads as it nears the viewport. Every other matched image – loading="eager" or no loading attribute at all – loads right away on the eager path.

Call lazyLoad() again after inserting images into the DOM to process the new ones. A call after the cleanup of an earlier one picks up the images that have not loaded yet, so a framework component can run lazyLoad on every mount or source change.

Pass lazyLoad an image with its own src or srcset and no data-src or data-srcset – the default selector skips it – and it keeps the sources and calls onImageLoad or onImageError once they settle. An image that loaded or failed before the call, for example before hydration, gets its callback too, unless an earlier call or reportImageOutcome already reported the same sources.

Type Declarations ​

ts
export interface UnLazyLoadOptions extends TriggerLoadOptions {
  /**
   * 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. Values above 100 are capped at 100.
   *
   * @remarks
   * This option is ignored if the `hashType` option is set to `thumbhash`.
   *
   * @default 32
   */
  placeholderSize?: number

  /**
   * Whether `data-sizes="auto"` should be resolved again when the rendered
   * width of the image changes. Applies to both `<img>` elements and their
   * `<source>` siblings inside a `<picture>`. Internally delegates to `autoSizes`.
   *
   * @default false
   */
  updateSizesOnResize?: boolean

  /**
   * Whether to load the image right away instead of when it nears the
   * viewport. The hash placeholder is decoded first and stays until the image
   * has loaded. Internally delegates to `triggerLoad`.
   *
   * @default false
   */
  preload?: boolean

  /**
   * Whether to hold the image on its hash placeholder and load nothing, even
   * with `preload` set. A later call without `hold` loads it. An image that has
   * loaded, or that has its own `src` or `srcset` and no `data-src` or
   * `data-srcset`, keeps its sources. A held image reports no outcome.
   *
   * @default false
   */
  hold?: boolean
}
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[data-src], img[data-srcset]'
   */
  selectorsOrElements?: string | T | NodeListOf<T> | T[],
  options?: UnLazyLoadOptions,
): () => void

Options ​

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, capped at 100. Ignored for ThumbHash.
updateSizesOnResizebooleanfalseRe-resolve data-sizes="auto" when the rendered size of the image changes – applies to both <img> and <source> siblings inside a <picture>. Internally delegates to autoSizes; the returned cleanup function disconnects every observer.
preloadbooleanfalseLoad lazy images right away instead of when they near the viewport. The hash placeholder is decoded first and stays until the image has loaded. Internally delegates to triggerLoad.
holdbooleanfalseHold the image on its hash placeholder and load nothing, even with preload set. A later call without hold loads it. An image that has loaded, or that has its own src or srcset and no data-src or data-srcset, keeps its sources. A held image reports no outcome.
onImageLoad(image: HTMLImageElement) => void-Callback invoked once the visible image has loaded its real source.
onImageError(image: HTMLImageElement, error: Event) => void-Callback invoked when an image fails to load. A lazy image keeps its placeholder, and the image gets a data-error attribute.

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()

How It Works ​

  1. Eager images get the priority path. For images not marked loading="lazy":
    • data-src / data-srcset swap into src / srcset immediately.
    • fetchpriority="high" is set if no value is already present.
    • No hash placeholder is decoded, since the real image would replace it before it is painted.
  2. Crawlers get the same immediate swap without a hash placeholder, so search engines 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. With preload: true, they load right away behind that placeholder.
  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. In development builds, unlazy warns if your LCP element is configured for lazy loading. See the Core Web Vitals guide.

Released under the MIT License.