Integrations
unlazy supports lazy loading images in your framework of choice. Each package provides a UnLazyImage
component as a drop-in replacement for the native <img>
element.
Generic How-To
To create a component for the framework of your choice, keep the following in mind:
- The component should wrap a native
<img>
element with theloading="lazy"
attribute set. - The component should support at least a
src
orsrcset
attribute. - Import the
lazyLoad
function from the unlazy library and call it with aHTMLImageElement
orHTMLSourceElement
as the first argument:
import { lazyLoad } from 'unlazy'
lazyLoad(target)
- If the component gets unmounted before the image is loaded, call the cleanup function returned by
lazyLoad
. Take the following example from the Vue integration:
import { lazyLoad } from 'unlazy'
const target = ref<HTMLImageElement | undefined>()
onMounted(() => {
if (target.value) {
const cleanup = lazyLoad(target.value)
onBeforeUnmount(cleanup)
}
})
That's it!
Server-Side Rendering
unlazy supports server-side rendering for BlurHash and ThumbHash strings. This means that you can generate the placeholder images for the src
attribute during SSR and avoid the Cumulative Layout Shift (CLS) caused by the images loading after the page has been rendered.
Both the unlazy/blurhash
and unlazy/thumbhash
exports provide a createPngDataUri
function that can be used to generate a PNG data URI for a BlurHash or ThumbHash string, respectively. This function can be used to generate the src
attribute for the <img>
element.
- BlurHash
createPngDataUri
– Generate a PNG data URI for a BlurHash string - ThumbHash
createPngDataUri
– Generate a PNG data URI for a ThumbHash string
TIP
The Nuxt integration uses this approach to enable the UnLazyImage
component to provide an SSR src
attribute for the initial render.
Available Integrations
The following integrations are available as of now: