Skip to content

Commit 528b48e

Browse files
feat: onLoad callback
1 parent e0bce76 commit 528b48e

File tree

1 file changed

+12
-3
lines changed

1 file changed

+12
-3
lines changed

src/index.ts

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,10 @@ export function lazyLoadImages(
77
* @default 'img[loading="lazy"]'
88
*/
99
selectors = 'img[loading="lazy"]',
10+
/**
11+
* A callback function to run when an image is loaded.
12+
*/
13+
onLoad?: (image: HTMLImageElement) => void,
1014
) {
1115
for (const image of [...document.querySelectorAll<HTMLImageElement>(selectors)]) {
1216
// Calculate the image's `sizes` attribute if `data-sizes="auto"` is set
@@ -20,17 +24,18 @@ export function lazyLoadImages(
2024
// Let the crawler load the image
2125
updatePictureSources(image)
2226
updateImageSrcset(image)
27+
onLoad?.(image)
2328
continue
2429
}
2530

2631
if (image.complete && image.naturalWidth > 0) {
2732
// Load the image if it's already in the viewport
28-
loadImage(image)
33+
loadImage(image, onLoad)
2934
continue
3035
}
3136

3237
// Otherwise, load the image when it enters the viewport
33-
image.addEventListener('load', () => loadImage(image), { once: true })
38+
image.addEventListener('load', () => loadImage(image, onLoad), { once: true })
3439
}
3540
}
3641

@@ -46,14 +51,18 @@ export function autoSizes(
4651
updateSizesAttribute(image)
4752
}
4853

49-
export function loadImage(image: HTMLImageElement) {
54+
export function loadImage(
55+
image: HTMLImageElement,
56+
onLoad?: (image: HTMLImageElement) => void,
57+
) {
5058
const imageLoader = new Image()
5159
imageLoader.srcset = image.dataset.srcset!
5260
imageLoader.sizes = image.sizes
5361

5462
imageLoader.addEventListener('load', () => {
5563
updatePictureSources(image)
5664
updateImageSrcset(image)
65+
onLoad?.(image)
5766
})
5867
}
5968

0 commit comments

Comments
 (0)