Skip to content

autoSizes

The autoSizes function resolves data-sizes="auto" to a numeric pixel width based on the rendered display size. It works on standalone <img> elements, on <source> siblings inside a <picture>, or both.

When called with an <img> inside a <picture>, autoSizes walks to every <source data-sizes="auto"> sibling and resolves them in the same call. <source> elements have no layout box of their own, so the rendered <img> width is used instead.

To lazy load images, refer to the lazyLoad method.

Options

OptionTypeDefaultDescription
updateOnResizebooleanfalseInstall a debounced ResizeObserver that re-resolves data-sizes="auto" on viewport changes. The returned cleanup function disconnects it.

Return Value

autoSizes returns a cleanup function. When called with updateOnResize: false (or no options), the cleanup is a no-op. With updateOnResize: true, calling it disconnects every ResizeObserver created by that call:

ts
import { autoSizes } from 'unlazy'

const cleanup = autoSizes('img[data-sizes="auto"]', { updateOnResize: true })

// Later, when cleaning up
cleanup()

Type Declarations

ts
export interface AutoSizesOptions {
  /**
   * Whether `data-sizes="auto"` should retrack the rendered width on viewport
   * resize. Sets up a debounced `ResizeObserver` per call; the returned
   * cleanup function disconnects it.
   *
   * @default false
   */
  updateOnResize?: boolean
}
ts
/**
 * Resolves `data-sizes="auto"` to a numeric pixel width. Given an `<img>`
 * inside a `<picture>`, walks to every `<source data-sizes="auto">` sibling and
 * resolves them too. With `{ updateOnResize: true }`, a debounced
 * `ResizeObserver` retracks the rendered width on viewport changes.
 *
 * @returns A cleanup function that disconnects every observer created by this call.
 * Calling it on a one-shot invocation is a no-op.
 */
export function autoSizes<T extends HTMLImageElement | HTMLSourceElement>(
  /**
   * A CSS selector, a DOM element, a list of DOM elements, or an array of DOM elements to calculate the `sizes` attribute for.
   *
   * @default 'img[data-sizes="auto"], source[data-sizes="auto"]'
   */
  selectorsOrElements?: string | T | NodeListOf<T> | T[],
  options?: AutoSizesOptions,
): () => void

Example

html
<img
  srcset="image-320w.jpg 320w, image-640w.jpg 640w"
  data-sizes="auto"
>
ts
import { autoSizes } from 'unlazy'

// One-shot resolve
autoSizes()

// Or: resolve and keep tracking on resize
const cleanup = autoSizes(undefined, { updateOnResize: true })

TIP

For most users, calling lazyLoad with updateSizesOnResize: true is the simpler path – it delegates to autoSizes internally and bundles the cleanup into the same callback.

Released under the MIT License.