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:
- If the image is inside a
<picture>element, updates all<source>elements by converting theirdata-srcsetanddata-sizesattributes to standard attributes synchronously. Callbacks fire after the browser resolves a source on the visible<img>. - For standalone
<img>elements, preloads the image in a temporary element to ensure proper loading. - Calculates the
sizesattribute ifdata-sizes="auto"is set. - Swaps
data-srcanddata-srcsetto their standard counterparts. - Invokes the optional
onImageLoadcallback when loading completes, oronImageErrorif loading fails. On failure, a syntheticerrorevent 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
},
): () => voidExample
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()