Skip to content

Usage ​

These guides build on the markup and the lazyLoad() call from Getting Started.

Calculate the sizes Attribute Automatically ​

Set data-sizes="auto", and unlazy sets the sizes attribute to the display width of the image:

html
<img
  loading="lazy"
  src="data:image/svg+xml, ..."
  data-srcset="image-320w.jpg 320w, image-640w.jpg 640w"
  data-sizes="auto"
  alt="Descriptive text"
  width="640"
  height="360"
/>

Alternatively, use the autoSizes function to calculate the sizes attribute without lazy loading. Call it with an <img> inside a <picture> and it walks to every <source data-sizes="auto"> sibling in the same call:

ts
import { autoSizes } from 'unlazy'

// One-shot resolve for every matching element in the document
autoSizes()

For responsive layouts where the display width changes – fluid containers, breakpoint switches, orientation changes – pass { updateOnResize: true } to keep sizes synced. autoSizes returns a cleanup function – call it when you no longer need the observer:

ts
const cleanup = autoSizes(undefined, { updateOnResize: true })

// Later, when unmounting
cleanup()

lazyLoad does the same with updateSizesOnResize: true, and the cleanup function it returns disconnects the observer too.

Target Specific Images ​

Both lazyLoad and autoSizes take a CSS selector, a DOM element, a list of DOM elements, or an array of DOM elements. To target images with a data-custom-lazy attribute, pass img[data-custom-lazy]:

ts
import { lazyLoad } from 'unlazy'

lazyLoad('img[data-custom-lazy]')

INFO

The loading="lazy" attribute is still required for the images to be lazy loaded.

Load an Image Manually ​

To load an image before it enters the viewport, call the triggerLoad function with the HTMLImageElement:

ts
import { triggerLoad } from 'unlazy'

const coolImage = document.querySelector<HTMLImageElement>('.image-to-load-first')!

// Trigger the load before the image enters the viewport
triggerLoad(coolImage)

TIP

Manually loading images may negatively affect perceived performance by forcing immediate load, even when not visible in the viewport.

Style a Failed Image ​

When an image fails to load, its placeholder stays – in a <picture> too – and the <img> gets a data-error attribute. Style the attribute to tell a failed image from one that is still loading:

css
img[data-error] {
  filter: grayscale(1);
  opacity: 0.5;
}

A later successful load removes data-error, for example after you set a new data-src and call triggerLoad again. An eager image has no placeholder to keep, so the browser shows its broken-image rendering, but it still gets data-error. So does a lazy image whose preload succeeds but whose visible <img> then fails to load the swapped-in source.

To react in code, pass onImageError. unlazy also dispatches an error event on the <img> first, so native onerror listeners fire as well:

ts
import { lazyLoad } from 'unlazy'

lazyLoad(undefined, {
  onImageError: (image, error) => {
    console.warn('Failed to load', image, error)
  },
})

The framework components set the same attribute and emit image-error (Vue, Nuxt) or call onImageError (React, Solid, Svelte).

Lazy Load <picture> Elements ​

unlazy fully supports the <picture> element for art direction and format selection. Each <source> element should use data-srcset instead of srcset:

html
<picture>
  <source
    type="image/avif"
    data-srcset="image-320w.avif 320w, image-640w.avif 640w"
    data-sizes="auto"
  />
  <source
    type="image/webp"
    data-srcset="image-320w.webp 320w, image-640w.webp 640w"
    data-sizes="auto"
  />
  <img
    loading="lazy"
    src="data:image/svg+xml, ..."
    data-src="image.jpg"
    data-srcset="image-320w.jpg 320w, image-640w.jpg 640w"
    data-sizes="auto"
    alt="Descriptive text"
    width="640"
    height="360"
  />
</picture>

When the image loads, unlazy automatically swaps data-srcset to srcset on all <source> elements within the <picture>. The onImageLoad callback fires once the visible <img> has loaded the selected source.

Released under the MIT License.