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 are not invoked for picture elements). - 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.
INFO
The loadImage function is a deprecated alias for triggerLoad and will be removed in the next major version.
Type Declarations
ts
/**
* Triggers the loading of a lazy image by swapping `data-src`/`data-srcset` to `src`/`srcset`.
*
* @remarks
* For standalone `<img>` elements, the image is preloaded via a temporary Image before
* swapping attributes, and callbacks are invoked accordingly.
*
* For `<img>` elements inside `<picture>`, attributes are swapped synchronously without
* preloading (the browser handles source selection). In this case, `onImageLoad` and
* `onImageError` callbacks are **not invoked**.
*/
export function triggerLoad(
image: HTMLImageElement,
onImageLoad?: (image: HTMLImageElement) => void,
onImageError?: (image: HTMLImageElement, error: Event) => void,
): voidExample
ts
import { triggerLoad } from 'unlazy'
const image = document.querySelector('.priority-image')
// Load immediately with callbacks
triggerLoad(
image,
img => console.log('Loaded:', img.src),
(img, error) => console.error('Failed to load:', img)
)