Today I Learned - Rocky Kev

TIL minimal responsive image component

POSTED ON:

TAGS:

Today, a image tag can look like this:

<img
src="small-image.png"
alt="A description of the image."
width="300"
height="200"
loading="lazy"
decoding="async"
srcset="small-image.png 1x, medium-image.png 2x, large-image.png 3x"
/>

My lord, look at those attributes!

So when I saw that JS frameworks made image wrapper components (like Nuxt was with <nuxt-img>), I was blown away and wanted this power at work.

What is it?
<nuxt-img> is a drop-in replacement for the native <img> tag:

via https://image.nuxtjs.org/components/nuxt-img

A minimal, multi-framework, responsive image component

How do we do it better?

This blog post: A minimal, multi-framework, responsive image component

This component does the following:

Here's the vue version:

<script setup lang="ts">
import { Image } from "@unpic/vue";
</script>

<template>
<Image
src="https://cdn.shopify.com/static/sample-images/bath_grande_crop_center.jpeg"
layout="constrained"
width="800"
height="600"
alt="A lovely bath"
/>
</template>

That generates:

<img
alt="A lovely bath"
loading="lazy"
decoding="async"
sizes="(min-width: 800px) 800px, 100vw"
style="object-fit: cover; max-width: 800px; max-height: 600px; aspect-ratio: 1.33333 / 1; width: 100%;"
srcset="
https://cdn.shopify.com/static/sample-images/bath.jpeg?crop=center&amp;width=1080&amp;height=1440 1080w,
https://cdn.shopify.com/static/sample-images/bath.jpeg?crop=center&amp;width=1280&amp;height=1707 1280w,
https://cdn.shopify.com/static/sample-images/bath.jpeg?crop=center&amp;width=1600&amp;height=2133 1600w,
https://cdn.shopify.com/static/sample-images/bath.jpeg?crop=center&amp;width=640&amp;height=853 640w,
https://cdn.shopify.com/static/sample-images/bath.jpeg?crop=center&amp;width=750&amp;height=1000 750w,
https://cdn.shopify.com/static/sample-images/bath.jpeg?crop=center&amp;width=800&amp;height=1067 800w,
https://cdn.shopify.com/static/sample-images/bath.jpeg?crop=center&amp;width=828&amp;height=1104 828w,
https://cdn.shopify.com/static/sample-images/bath.jpeg?crop=center&amp;width=960&amp;height=1280 960w
"

src="https://cdn.shopify.com/static/sample-images/bath.jpeg?width=800&amp;height=600&amp;crop=center"
/>

Related TILs

Tagged:

TIL minimal responsive image component

So when I saw that JS frameworks made image wrapper components (like Nuxt was with nuxt-img), I was blown away and wanted this power at work.

TIL minimal responsive image component

So when I saw that JS frameworks made image wrapper components (like Nuxt was with nuxt-img), I was blown away and wanted this power at work.

TIL minimal responsive image component

So when I saw that JS frameworks made image wrapper components (like Nuxt was with nuxt-img), I was blown away and wanted this power at work.