:warning: You probably don't need this: With native
loading="lazy"
image support on all evergreen browsers, all this library really offers now is srcset generation for imgix images. For that there's now the standalone imgix-srcset JS utility which can also be serverside rendered
Svelte action for generating responsive, lazily-loaded images with Imgix
srcsets
automaticallynpm i svelte-imgix
<script>
import imgix from 'svelte-imgix';
</script>
<img use:imgix="https://assets.imgix.net/unsplash/vintagecameras.jpg" />
Rather than passing a src
image to use:imgix
, you can pass a full configuration object with the following properties
Property | Default | Description |
---|---|---|
src |
'' |
Src of the image |
lazyload |
false |
Delay loading the full res image until it's in view |
imgixProps |
{} |
Additional imgix properties to pass to the image |
<img use:imgix={{
src: 'https://assets.imgix.net/unsplash/vintagecameras.jpg',
lazyload: false,
imgixParams: {
fit: 'crop',
ar: '16:9'
}
}} />
Svelte Imgix exports 2 additional helpers that you can use to create responsive source sets and LQIP placeholders yourself, srcset(src)
and placeholder(src)
;
<script>
import { placeholder, srcset } from 'svelte-imgix';
import { invew } from 'svelte-inview';
let src = '';
let intersected = false;
</script>
<img src={intersected ? src : placeholder(src)} srcset={intersected ? srcset(src} : ''} use:invew on:enter={() => intersected = true} />
Until Svelte supports actions running in SSR, you might notice images don't have a src at all until svelte-imgix
has hydrated. As a workaround, use the placeholder
helper function to SSR an LQIP placeholder image manually. Svelte-imgix will then hydrate from there, with the same placeholder image, and load your full srcset once the image enters the viewport.
<img use:imgix={src} src={placeholder(src)} />
Svelte-Imgix automatically generates a responsive srcset
for a huge range of viewport sizes. By adding a sizes
attribute to your image you can instruct the browser to use the appropriate source based on media queries.
See the MDN article on responsive images for a thorough walkthrough.