Skip to content

triggerLoad

The triggerLoad function programmatically loads an image by updating its attributes from data attributes. It handles both standalone <img> elements and images within <picture> elements.

The function performs the following operations:

  1. If the image is inside a <picture> element, updates all <source> elements by converting their data-srcset and data-sizes attributes to standard attributes synchronously. Callbacks fire after the browser resolves a source on the visible <img>.
  2. For standalone <img> elements, preloads the image in a temporary element to ensure proper loading.
  3. Calculates the sizes attribute if data-sizes="auto" is set.
  4. Swaps data-src and data-srcset to their standard counterparts.
  5. Invokes the optional onImageLoad callback when loading completes, or onImageError if loading fails. On failure, a synthetic error event also fires on the visible <img>.

triggerLoad returns a disposer that detaches its listeners and, for standalone images, aborts the in-flight network fetch. Calling it after the load has already completed is a no-op.

Type Declarations

ts
/**
 * Triggers the loading of a lazy image by swapping `data-src`/`data-srcset` to `src`/`srcset`.
 *
 * @returns A disposer that detaches listeners and, for standalone images, aborts any
 * in-flight network fetch by clearing the temporary image's `src`. Calling it after the
 * load completes is a no-op.
 *
 * @remarks
 * For standalone `<img>` elements, the image is preloaded via a temporary `Image` before
 * the swap; `onImageLoad` fires on success and `onImageError` on failure. On failure unlazy
 * also dispatches a synthetic `error` event on the visible `<img>` so consumers using
 * native `addEventListener('error', …)` or framework-native `onError` / `@error` get notified.
 *
 * For `<img>` elements inside `<picture>`, the browser handles source selection. Listeners
 * are attached on the visible `<img>` before the swap so the queued `load` task is caught
 * once the browser resolves a source.
 */
export function triggerLoad(
  image: HTMLImageElement,
  options?: {
    onImageLoad?: (image: HTMLImageElement) => void
    onImageError?: (image: HTMLImageElement, error: Event) => void
  },
): () => void

Example

ts
import { triggerLoad } from 'unlazy'

const image = document.querySelector<HTMLImageElement>('.priority-image')!

// Load immediately with callbacks
const dispose = triggerLoad(image, {
  onImageLoad: img => console.log('Loaded:', img.src),
  onImageError: (img, error) => console.error('Failed to load:', img, error),
})

// Later, cancel the load if it hasn't completed yet
dispose()

Released under the MIT License.