Getting Started
unlazy is a lazy loading library that leverages native browser APIs. It uses inlined placeholder images or hash-based representations like BlurHash or ThumbHash alongside the native loading="lazy" attribute, and targets Baseline Widely Available browsers.
Images render with blurry placeholders initially, then swap to full-quality versions as they enter the viewport. This improves perceived performance, especially on slow connections.
Install unlazy
Install the unlazy package using your favorite package manager:
pnpm add -D unlazyyarn add -D unlazynpm install -D unlazyMark Up an Image
Add the
loading="lazy"attribute to an<img>element that you want to lazily load. You can also use the<picture>element to lazily load images in different formats.Use
data-srcordata-srcsetattributes to specify the high-quality image. These prevent browsers from loading images before they enter the viewport and are swapped to standard attributes when loading occurs.Set the
srcattribute with a pre-generated blurry placeholder, or use hash-based placeholders (BlurHash or ThumbHash) to generate placeholders on the fly.
<img
loading="lazy"
src="blurry placeholder ..."
data-srcset="image.png"
data-sizes="auto"
alt="Descriptive text"
width="1200"
height="800"
>With data-srcset, set data-sizes="auto" to calculate the sizes attribute automatically.
Call lazyLoad
In your frontend code, import the lazyLoad function from the library and call it:
import { lazyLoad } from 'unlazy'
// Lazily load all `img[loading="lazy"]` images
const cleanup = lazyLoad()The lazyLoad function returns a cleanup function that removes event listeners and ResizeObservers. Call this when unmounting components or removing images to prevent memory leaks.
Images that are visible in the initial viewport – your hero / LCP image in particular – should not be lazy-loaded. Mark them loading="eager" instead (see The Eager Path).
From here, Usage covers more use cases, and Hash-Based Placeholders sets up BlurHash or ThumbHash placeholders.