triggerLoad
The triggerLoad function loads an image right away by swapping its data-src and data-srcset to src and srcset. It works on a standalone <img> and on an <img> inside a <picture>.
Example
ts
import { triggerLoad } from 'unlazy'
const image = document.querySelector<HTMLImageElement>('.priority-image')!
// Load immediately with callbacks
const cleanup = 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 has not completed yet
cleanup()Type Declarations
ts
export interface TriggerLoadOptions {
/** Runs once the visible `<img>` has loaded the swapped-in source. */
onImageLoad?: (image: HTMLImageElement) => void
/**
* Runs when the image fails to load. The visible `<img>` receives an `error`
* event first, even when only the preload failed.
*/
onImageError?: (image: HTMLImageElement, error: Event) => void
}ts
/**
* Loads a lazy image right away, even far from the viewport, by swapping
* `data-src`/`data-srcset` to `src`/`srcset`.
*
* @returns A cleanup function that detaches listeners and aborts any in-flight preload fetch.
* Calling it after the load completes is a no-op.
*/
export function triggerLoad(
image: HTMLImageElement,
options?: TriggerLoadOptions,
): () => voidHow It Works
- Resolves
data-sizes="auto"to a numeric pixel width on the<img>and on every<source>of its<picture>. - Preloads the image in a temporary
<img>that copies thereferrerpolicy,crossorigin,fetchpriority, anddecodingattributes of the visible one. The matchingreferrerpolicyandcrossoriginlet the browser fetch the image once. For an<img>inside a<picture>, the temporary image sits in a detached copy of the<picture>and fetches the source the browser selects. - Once the preload has loaded, sets
loading="eager"on the visible<img>, so an off-screen image loads too, and swapsdata-srcanddata-srcset– on the<img>and on every<source>– to their standard counterparts. - Invokes the optional
onImageLoadcallback once the visible<img>has loaded the new source. - If the preload fails, swaps nothing: the placeholder stays, the visible
<img>gets adata-errorattribute and a syntheticerrorevent, thenonImageErrorruns. If the preload loads but the visible<img>then fails to load the swapped-in source, it getsdata-errortoo, andonImageErrorruns with the<img>'s ownerrorevent. See Style a Failed Image.
TIP
triggerLoad is one-shot – it does not install any ResizeObserver. For ongoing source-size tracking on responsive <picture> layouts, pair it with autoSizes and { updateOnResize: true }:
ts
const cleanupSizes = autoSizes(image, { updateOnResize: true })
const cleanupLoad = triggerLoad(image)
// Later
cleanupSizes()
cleanupLoad()