Skip to content

Commit 207be68

Browse files
fix: ensure a fallback src is present for loading="lazy" (fixes #26)
1 parent 6903fe8 commit 207be68

File tree

3 files changed

+17
-3
lines changed

3 files changed

+17
-3
lines changed

packages/core/src/constants.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
11
export const DEFAULT_PLACEHOLDER_SIZE = 32
2+
export const DEFAULT_IMAGE_PLACEHOLDER = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'

packages/core/src/lazyLoad.ts

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { DEFAULT_PLACEHOLDER_SIZE } from './constants'
1+
import { DEFAULT_IMAGE_PLACEHOLDER, DEFAULT_PLACEHOLDER_SIZE } from './constants'
22
import { debounce, isCrawler, isLazyLoadingSupported, toElementArray } from './utils'
33
import { createPngDataUri as createPngDataUriFromThumbHash } from './thumbhash'
44
import { createPngDataUri as createPngDataUriFromBlurHash } from './blurhash'
@@ -63,8 +63,13 @@ export function lazyLoad<T extends HTMLImageElement>(
6363
continue
6464
}
6565

66+
// Ensure that `loading="lazy"` works correctly by setting the `src`
67+
// attribute to a transparent 1x1 pixel
68+
if (!image.src)
69+
image.src = DEFAULT_IMAGE_PLACEHOLDER
70+
71+
// Load the image if it's already in the viewport
6672
if (image.complete && image.naturalWidth > 0) {
67-
// Load the image if it's already in the viewport
6873
loadImage(image, onImageLoad)
6974
continue
7075
}

packages/unlazy/src/index.ts

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,10 @@
1-
export { autoSizes, createPlaceholderFromHash, isCrawler, isLazyLoadingSupported, lazyLoad, loadImage, updateSizesAttribute } from '@unlazy/core'
1+
export {
2+
autoSizes,
3+
createPlaceholderFromHash,
4+
isCrawler,
5+
isLazyLoadingSupported,
6+
lazyLoad,
7+
loadImage,
8+
updateSizesAttribute,
9+
} from '@unlazy/core'
210
export type { UnLazyLoadOptions } from '@unlazy/core'

0 commit comments

Comments
 (0)