loadImage
The loadImage 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 - 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 callback when loading completes
Type Declarations
ts
export function loadImage(
image: HTMLImageElement,
onImageLoad?: (image: HTMLImageElement) => void
): void