Skip to content

Commit d7ac90a

Browse files
docs: update documentation for image loading features and placeholder generation
1 parent ffa68fd commit d7ac90a

20 files changed

+287
-99
lines changed

docs/advanced/aspect-ratio.md

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
# Aspect Ratio for Blurry Placeholders
22

3-
In certain cases, the blurry placeholder might not have the full image width and height. To ensure that the layout does not change when the full-quality image loads and to maintain a consistent user experience, you can add the `aspect-ratio` CSS property to the `style` attribute to your images.
3+
When using blurry placeholders without explicit `width` and `height` attributes, the browser doesn't know the image dimensions until it loads, causing Cumulative Layout Shift (CLS). Setting the `aspect-ratio` CSS property reserves the correct space before the full-quality image loads.
44

5-
By setting the aspect ratio for your blurry placeholders, you can:
5+
This technique is especially important for:
66

7-
- Prevent layout shifts as the full-quality image loads.
8-
- Ensure that the image container maintains its dimensions even before the full-quality image is loaded.
7+
- Preventing CLS and improving Core Web Vitals scores
8+
- Maintaining consistent layouts during image loading
9+
- Supporting responsive images where dimensions vary by viewport
910

1011
## Usage
1112

docs/advanced/build-flags.md

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
# Build Flags
22

3-
This guide will focus on build flags to enable bundlers like [Rollup](https://rollupjs.org) to tree-shake features that are not used in your project.
3+
unlazy uses build-time flags to enable tree-shaking of unused features, reducing bundle size. Bundlers replace these flags at build time, allowing dead code elimination for features your project doesn't use.
44

5-
Most bundlers provide a `define` option to set build flags:
5+
Common bundlers support the `define` option for setting build flags:
66

77
- [Vite](https://vitejs.dev/config/shared-options.html#define)
88
- [@rollup/plugin-replace](https://www.npmjs.com/package/@rollup/plugin-replace)
@@ -26,16 +26,17 @@ export default defineConfig({
2626

2727
## Disable Hash Decoding <Badge type="info" text="^0.10.0" />
2828

29-
unlazy ships with the [BlurHash](/placeholders/blurhash) and [ThumbHash](/placeholders/thumbhash) decoding algorithms to decode the hash values into images.
29+
unlazy includes [BlurHash](/placeholders/blurhash) and [ThumbHash](/placeholders/thumbhash) decoding algorithms (from `fast-blurhash` and `thumbhash` packages). If your project doesn't use hash-based placeholders, you can exclude these dependencies entirely:
3030

31-
In case your project does not use these placeholders, you can disable the hash decoding algorithms to reduce the bundle size. Use the following build flags to tree-shake the hash decoding algorithms:
31+
- `__UNLAZY_HASH_DECODING__`: Set to `false` to tree-shake hash decoding code. Default is `true`.
3232

33-
- `__UNLAZY_HASH_DECODING__`: This flag is set to `true` by default.
33+
When disabled, the bundler removes:
34+
- BlurHash and ThumbHash decoding libraries
35+
- Hash-related code paths in `lazyLoad()`
36+
- Associated dependencies from the final bundle
3437

3538
::: warning
36-
This will only tree-shake the BlurHash and ThumbHash decoding algorithms when using the [`lazyLoad`](/api/lazy-load) method.
37-
38-
If you use either `unlazy/blurhash` or `unlazy/thumbhash` sub-path imports directly, the decoding algorithms will still be bundled.
39+
This flag only affects the main entry point. If you directly import `unlazy/blurhash` or `unlazy/thumbhash`, those modules will still be bundled regardless of this flag.
3940
:::
4041

4142
## Disable Client Logging <Badge type="info" text="^0.10.2" />

docs/api/auto-sizes.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
# `autoSizes`
22

3-
The `autoSizes` function calculates the sizes attribute for a CSS selector, a DOM element, a list of DOM elements, or an array of DOM elements if the `data-sizes` attribute is set to `auto`.
3+
The `autoSizes` function calculates and sets the `sizes` attribute based on the current display width of image or source elements when `data-sizes="auto"` is present.
4+
5+
The calculation uses the element's rendered width (`element.offsetWidth`) to determine the appropriate value for the `sizes` attribute, enabling browsers to select the optimal image from a `srcset`.
46

57
To lazy load images, refer to the [`lazyLoad`](/api/lazy-load) method.
68

docs/api/blurhash-create-png-data-uri.md

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,18 @@
11
# `createPngDataUri`
22

3-
Especially when using a server-side rendering framework like [Nuxt](https://nuxt.com), you might want to generate the placeholder images for the `src` attribute during SSR. This can be done with the `createPngDataUri` function:
3+
Creates a PNG data URI from a BlurHash string for server-side rendering. This function decodes the BlurHash into RGBA pixel data and encodes it as a base64 PNG data URI.
44

55
```ts
66
import { createPngDataUri } from 'unlazy/blurhash'
77

8-
const pngDataUri = createPngDataUri(blurhash)
8+
const pngDataUri = createPngDataUri(blurhash, {
9+
ratio: 16 / 9,
10+
size: 32
11+
})
912
```
1013

14+
The function uses the `fast-blurhash` library for decoding and generates a compact PNG representation suitable for inlining in HTML.
15+
1116
## Type Declarations
1217

1318
```ts
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
# `createPlaceholderFromHash`
2+
3+
Generates a PNG data URI placeholder from a BlurHash or ThumbHash string. This function is used internally by [`lazyLoad`](/api/lazy-load) but can also be called directly for custom implementations.
4+
5+
## Type Declarations
6+
7+
```ts
8+
function createPlaceholderFromHash(options?: {
9+
/** If present, hash and ratio are extracted from element's data attributes */
10+
image?: HTMLImageElement
11+
/** Hash string to decode */
12+
hash?: string
13+
/** Type of hash algorithm */
14+
hashType?: 'blurhash' | 'thumbhash'
15+
/** Size of longer edge for BlurHash decoding (ignored for ThumbHash) */
16+
size?: number
17+
/** Aspect ratio (width/height) for BlurHash */
18+
ratio?: number
19+
}): string | undefined
20+
```
21+
22+
## Parameters
23+
24+
The function accepts an options object with the following properties:
25+
26+
- `image`: If provided, the function extracts the hash from `data-blurhash` or `data-thumbhash` attributes and calculates the aspect ratio from the element's dimensions
27+
- `hash`: The hash string to decode. If both `image` and `hash` are provided, `hash` takes precedence
28+
- `hashType`: Specifies whether the hash is a `blurhash` or `thumbhash`. Default is `blurhash`. If `image` is provided, the type is determined from the presence of `data-blurhash` or `data-thumbhash` attributes
29+
- `size`: The size of the longer edge for BlurHash decoding. Default is `32`. This parameter is ignored for ThumbHash
30+
- `ratio`: The aspect ratio (width divided by height) for BlurHash. If `image` is provided, this is calculated automatically from the element's dimensions
31+
32+
## Return Value
33+
34+
Returns a PNG data URI string if the hash is successfully decoded, or `undefined` if:
35+
- No hash is provided
36+
- The hash decoding fails
37+
- The required decoding library is not available
38+
39+
## Examples
40+
41+
Using with a hash string:
42+
43+
```ts
44+
import { createPlaceholderFromHash } from 'unlazy'
45+
46+
const placeholder = createPlaceholderFromHash({
47+
hash: 'LKO2:N%2Tw=w]~RBVZRi};RPxuwH',
48+
hashType: 'blurhash',
49+
size: 32,
50+
ratio: 16 / 9
51+
})
52+
```
53+
54+
Using with an image element:
55+
56+
```ts
57+
import { createPlaceholderFromHash } from 'unlazy'
58+
59+
const img = document.querySelector('img')
60+
const placeholder = createPlaceholderFromHash({
61+
image: img
62+
})
63+
64+
if (placeholder) {
65+
img.src = placeholder
66+
}
67+
```
68+
69+
::: tip
70+
For server-side rendering, use the specialized functions instead:
71+
- [`createPngDataUri`](/api/blurhash-create-png-data-uri) from `unlazy/blurhash`
72+
- [`createPngDataUri`](/api/thumbhash-create-png-data-uri) from `unlazy/thumbhash`
73+
:::

docs/api/index.md

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,10 @@
22

33
unlazy provides a number of methods to help you with lazy loading images. The following methods are available:
44

5-
- [`lazyLoad`](/api/lazy-load) – Lazy load images
5+
- [`lazyLoad`](/api/lazy-load) – Lazy load images with automatic placeholder generation
66
- [`autoSizes`](/api/auto-sizes) – Automatically calculate the `sizes` attribute
7-
- [`loadImage`](/api/load-image) – Manually load an image
7+
- [`loadImage`](/api/load-image) – Manually load an image before it enters the viewport
8+
- [`createPlaceholderFromHash`](/api/create-placeholder-from-hash) – Generate PNG data URI from BlurHash or ThumbHash
89

910
## Server-Side Rendering
1011

docs/api/lazy-load.md

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,24 @@ The `lazyLoad` function takes a CSS selector, a DOM element, a list of DOM eleme
1515

1616
## Options
1717

18-
Options can be passed to the function to customize its behavior. These options include:
18+
Options can be passed to the function to customize its behavior:
1919

20-
- `hash`: Whether to use a hash for generating a blurry placeholder. Default is `true`.
21-
- `hashType`: The type of hash to use for generating a blurry placeholder. Possible values are `blurhash` and `thumbhash`. Default is `blurhash`.
22-
- `placeholderSize`: The size of the placeholder. Applies only to BlurHash strings. Default is `32`.
23-
- `onImageLoad`: A callback function that will be executed when the image is loaded.
20+
- `hash`: Whether to use a hash for generating a blurry placeholder. Can be a boolean or a string. Default is `true`. If `thumbhash` is provided, it takes precedence over `blurhash`.
21+
- `hashType`: The type of hash to use. Possible values are `blurhash` and `thumbhash`. Default is `blurhash`.
22+
- `placeholderSize`: The size of the longer edge for BlurHash decoding. Default is `32`. Ignored for ThumbHash.
23+
- `updateSizesOnResize`: Whether to update the `sizes` attribute on window resize events using a debounced ResizeObserver. Default is `false`.
24+
- `onImageLoad`: A callback function invoked when an image loads successfully.
25+
26+
## Return Value
27+
28+
The function returns a cleanup function that removes all event listeners and ResizeObservers created by `lazyLoad`. Call this function when images are no longer needed to prevent memory leaks:
29+
30+
```ts
31+
const cleanup = lazyLoad()
32+
33+
// Later, when cleaning up
34+
cleanup()
35+
```
2436

2537
## Type Declarations
2638

docs/api/load-image.md

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,14 @@
11
# `loadImage`
22

3-
The `loadImage` function takes an `HTMLImageElement` and an optional callback function to execute when the image is loaded. It updates the `src`, `srcset`, and `sizes` attributes of the image and its parent picture element's sources, if applicable.
3+
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.
4+
5+
The function performs the following operations:
6+
7+
1. If the image is inside a `<picture>` element, updates all `<source>` elements by converting their `data-srcset` and `data-sizes` attributes to standard attributes
8+
2. Preloads the image in a temporary element to ensure proper loading
9+
3. Calculates the `sizes` attribute if `data-sizes="auto"` is set
10+
4. Swaps `data-src` and `data-srcset` to their standard counterparts
11+
5. Invokes the optional callback when loading completes
412

513
## Type Declarations
614

docs/api/thumbhash-create-png-data-uri.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
11
# `createPngDataUri`
22

3-
Especially when using a server-side rendering framework like [Nuxt](https://nuxt.com), you might want to generate the placeholder images for the `src` attribute during SSR. This can be done with the `createPngDataUri` function:
3+
Creates a PNG data URI from a ThumbHash string for server-side rendering. This function decodes the base64-encoded ThumbHash into RGBA pixel data and encodes it as a base64 PNG data URI.
44

55
```ts
66
import { createPngDataUri } from 'unlazy/thumbhash'
77

88
const pngDataUri = createPngDataUri(thumbhash)
99
```
1010

11+
The function handles base64-url encoding by converting `-` to `+` and `_` to `/` before decoding. It uses the `thumbhash` library for decoding, which automatically determines the aspect ratio from the hash itself.
12+
1113
## Type Declarations
1214

1315
```ts

docs/guide/index.md

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,17 @@ Although the `loading="lazy"` attribute is supported in all major browsers, it i
1010

1111
## How It Works
1212

13-
unlazy processes all images with a `loading="lazy"` attribute, calculates the sizes attribute if necessary, and checks if the image has a blurry placeholder (given that either a `data-src` or `data-srcset` attribute is present).
13+
unlazy enhances the native `loading="lazy"` attribute by processing images and managing their lifecycle:
1414

15-
unlazy intends to offer a good balance between performance and user experience and works well for specific use cases where blurry placeholders are the preferred method for image loading.
15+
1. **Data Attribute Processing**: Uses `data-src`, `data-srcset`, and `data-sizes` attributes which are swapped to standard attributes when images load. This prevents browsers from eagerly loading images before they enter the viewport.
16+
17+
2. **Placeholder Generation**: Decodes [BlurHash](/placeholders/blurhash) or [ThumbHash](/placeholders/thumbhash) strings (via `data-blurhash` or `data-thumbhash` attributes) into PNG data URIs for placeholders.
18+
19+
3. **Chrome Workaround**: Generates unique indexed SVG placeholders to prevent Chrome's aggressive image loading behavior that can trigger load events prematurely.
20+
21+
4. **Automatic Sizes Calculation**: Calculates the `sizes` attribute based on the image's display width when `data-sizes="auto"` is set.
22+
23+
unlazy leverages native browser APIs rather than replacing them, offering a good balance between performance and user experience for image-heavy applications.
1624

1725
## SEO
1826

0 commit comments

Comments
 (0)