Skip to content

createPlaceholderFromHash ​

Generates a PNG data URI placeholder from a BlurHash or ThumbHash string, the same placeholder lazyLoad sets.

Example ​

Using with a hash string:

ts
import { createPlaceholderFromHash } from 'unlazy'

const placeholder = createPlaceholderFromHash({
  hash: 'LKO2:N%2Tw=w]~RBVZRi};RPxuwH',
  hashType: 'blurhash',
  size: 32,
  ratio: 16 / 9
})

Using with an image element:

ts
import { createPlaceholderFromHash } from 'unlazy'

const img = document.querySelector('img')!
const placeholder = createPlaceholderFromHash({
  image: img
})

if (placeholder) {
  img.src = placeholder
}
html
<img
  width="800"
  height="600"
  data-blurhash="LKO2:N%2Tw=w]~RBVZRi};RPxuwH"
>

TIP

For server-side rendering, use the specialized functions instead:

Type Declarations ​

ts
export interface CreatePlaceholderFromHashOptions {
  /**
   * Image to read the hash from its `data-thumbhash` or `data-blurhash`
   * attribute, and the ratio from its width and height.
   */
  image?: HTMLImageElement
  hash?: string
  hashType?: 'blurhash' | 'thumbhash'
  /**
   * Longer edge of a BlurHash placeholder in pixels. Values above 100 are
   * capped at 100.
   *
   * @default 32
   */
  size?: number
  /**
   * Aspect ratio (width / height) of a BlurHash placeholder. Read from `image`
   * when both its width and height are known, otherwise square.
   */
  ratio?: number
}
ts
export function createPlaceholderFromHash(options?: CreatePlaceholderFromHashOptions): string | undefined

Options ​

OptionTypeDefaultDescription
imageHTMLImageElement-If provided, extracts hash from data-blurhash or data-thumbhash and calculates ratio from element dimensions
hashstring-Hash string to decode. Takes precedence over image attributes
hashType'blurhash' | 'thumbhash''blurhash'Hash format. Auto-detected when image is provided without hash
sizenumber32Size of the longer edge for BlurHash decoding, capped at 100. Ignored for ThumbHash
rationumber-Aspect ratio (width / height) for BlurHash. Read from image when both its width and height are known, otherwise 1 (square)

INFO

For BlurHash, set explicit width and height attributes on images. See Hash-Based Placeholders for why.

Return Value ​

Returns a PNG data URI string, or undefined if no hash is provided or the decoder throws. Unlike the placeholders lazyLoad sets, the data URI carries no unique fragment – before you set it on several lazy images, give each its own.

Released under the MIT License.