After finding your feet with SvelteKit, probably one of the most sought after features is a SvelteKit image plugin. If you are coming from a React background you might be thinking of something along the lines of next/image . The great news is that there is a plugin for generating Next-Gen, responsive images in SvelteKit. The bonus is you don't sacrifice SvelteKit's lightning fast development experience to use it.
In this post we take a look at how you can leverage the slick Vite environment at the heart of
SvelteKit to generate Next-Gen, responsive images. We also look at some techniques pioneered by
image optimisation guru Addy Osmani to minimise Cumulative Layout Shift. If you you don't yet know what that is don't worry we'll visit
some of the terms used here next. We'll also have a brief introduction to the
Responsive is just a way of saying your app adjusts to the user device's display width. This means the buttons are not so small that when you open the app on your phone it's difficult to press them. Responsiveness is a ranking factor for Google mostly because responsive sites create great user experience. Responsive images scale down to fit the browser window width (so you don't have to scroll across to the see the rest of the image or have it abruptly cropped). For these devices, with smaller screens, we can safely serve a lower resolution image. This will be smaller, allowing the page to load faster. Which brings us back to enhanced user experience.
Talking of serving smaller images, that's what Next-Gen images are all about. WebP (which we focus on today) as well as AVIF and JPEG XL format images are created using algorithms designed to preserve image quality while shrinking the image size. Although WebP celebrates wider support that its newer cousins AVIF and JPEG XL, none of these are supported by older browsers. This means to play it safe, when we serve Next-Gen images we also include a fallback in our markup. The fallback is shown if the other formats are not supported by the user's browser. You can set a fallback chain, trying JPEG XL first, then falling back to AVIF, then WebP and finally if all else failed JPEG (or PNG).
Most popular sites today are well-designed. There are still a few that can be a little frustrating to use because of cumulative layout shift. This is when the page is slow to load, you get impatient and hit a button while waiting to interact. Just as you hit the button (but too late for you to pull out of the button press), the layout changes. You push a button or click a link you didn't intend to. Now a page you have no interest in at all is loading (slowly) and you have to wait to go back, re-click and then wait again while the page you actually wanted loads.
What an awful user experience! Which is why cumulative layout shift is a core metric used by Google's page ranking algorithm. Pictures can be a cause of CLS. We will see that if we add a placeholder (smaller file which takes up the same layout space as the ultimate image) we can eliminate Cumulative Layout Shift.
This is important where you have a lot of content to load on a page. Lazy loading is a way for us, as developers, to tell the browser which images to focus on and which it can wait until the user scrolls down. Imagine an Instagram feed. You can scroll down and eventually see hundreds of images. However when you first open up the feed, you only need to see a handful of images. If the device tried to load all of the hundreds of images in the feed initially, you would have to wait forever even to see the handful of images at the top of the feed (as it tried to load all of the images).
A more sensible approach is to focus on loading the images in view and lazy load the others (this
is something like
client:visible hydration when using Astro). In other words, wait for the user to scroll down before loading another handful of images. We
can load our placeholders initially (these will be smaller that ultimate image) and defer loading
the actual image until it is needed.
We will dovetail all these techniques together to create the ultimate user experience. This should lead to higher ranking for our site pages.
We'll start with the SvelteKit MDsveX starter and add a responsive image to the home page. We will see how you can generate a low resolution placeholder as well as an alternative dominant colour placeholder. We will generate a WebP Next-Gen format image together with the original JPEG in different sizes so the image looks good on large retina displays without having to download a huge image for small mobile displays. Using the placeholders, we will eliminate image layout shift.
If that all sounds good, then why don't we get cracking?
To get the ball rolling, clone the MDsveX SvelteKit starter and get your local clone ready for development:
Here we clone the repo into a new directory, change into that directory, install packages and
create some placeholder environment variables. Finally we spin up the dev server. Swap
npm if you prefer npm or use the yarn equivalent, if you are
a yarn person.
We will need a couple of packages later, let's install them now:
We are installing the same version of sharp here which is used in
vite-imagetools (see below). I was getting some build errors when I tried to use the latest version (currently 0.29.3).
We will use sharp to help create the placeholder images.
We are also using
vite-imagetools . This is already included in the repo. If you are following along on your own existing project,
vite-imagetools now. Also see how to configure it in your
svelte.config.js file (no need to do this if you cloned the starter as described above):
svelte.config.js — click to expand code.
Now let's add a JPEG, as a starting point. Download the file
me.jpg and save it in the
src/lib/assets/ directory in the project. That
image is 1344 pixels wide. We will display the image at a maximum width of 672 px and need
the input to be double that to cater for retina displays. The next step is to render the image, edit
Here we import the the image into the
meImage variable. Note we added
a query string onto the end:
vite-imagetools will process the import and generate a 672 pixel wide output for us. This will be our base
fallback image, we will include the 1344 px wide retina image later. SvelteKit will copy the image
to the build directory and cache it. For now, working on the dev server, the
meImage variable just links to a temporary file. You can see this if you
console log it. As the variable points to the image source we want to use, we can use it as the
src attribute in an
img tag. Let's do that next:
There is a lot to remember in setting up responsive images and I find this tweet from Addy Osmani really helpful:
We will work towards something along those lines. Anyway, going back to the
img element we just created, you are probably already aware the
attribute is important for users with visual impairments and describes the image.
loading attribute can be
eager (default) or
lazy. This determines whether the browser defers
loading until the image is in the viewport. As a rule of thumb, the largest image, initially in
the visible viewport (before the user scrolls down), should be
eager loading. This is so that the page looks interactive quicker. Any other images can be set to
lazy. Here, since we want to see how to set up a lazy loading image in our example we will set it to
lazy, even though our image is initially in the visible viewport.
loading is is not supported by all browsers so we have a couple more lazy loading tricks later.
decoding attribute set to
async hints that the browser should start decoding the image and immediately continue parsing the remaining
content, rather than waiting for decode to complete before proceeding. This is another measure to improve
user experience, so we get more content visible quicker.
Finally, it is important to set
width, to reduce cumulative layout shift. By setting both height and width, the browser knows the
aspect ratio of the image and can reserve the right amount of space for it in the layout while it
waits for it to load. Read more about
img element tags from MDN .
Let's also update the styling of the image at the bottom of our home page file:
Placeholders are another trick for reducing cumulative layout shift. To do this they need to be exactly the same size as the actual image (though they are typically lower resolution). On top they make the page look more interesting, while the actual image loads, again improving user experience.
We will use the sharp imaging plugin to generate the placeholders. sharp will encode these as Base64 strings for us. We will make our placeholder generation functions available via a server endpoint. Within
the load function (first
script block) on our page, we load the placeholders before
we render the page. Let's tackle things in that order.
The starter already includes some image utility functions. Let's take a look at
src/lib/utilities/image.js (no need to change anything in the project here):
We are using
await here. As an
example, in line
6, generating the image stats might not be
asynchronously, which means it won't wait for the result of line
before starting work on line
7, (it just starts execution and
hopes for the best!). This is different to how code generated by many other languages runs.
To help us out the sharp library authors implemented the
to return a promise instead of the result. A promise will either fail or eventually resolve to the
result. By including the keyword
await, we tell the server not to
continue to line
7 until the promise is resolved and we have a result.
Whenever we use the
await keyword in a function, we also need to add
async keyword to the function signature (you can see this in line
3). Finally, since the promise can fail, it is a good idea to wrap
the block in a
dominantColour function uses the sharp library and we can use the
result to generate a placeholder which is a block in a single colour, much like the image placeholders
you see on Twitter. Let's create a function which uses it to generate a 3 px × 2 px
image (same aspect ratio as our originals):
lowResolutionPlaceholder function resizes the input to
ten pixels wide and reduces the quality. See sharp API docs on resizing images if you want to tweak the parameters for your own project. Both functions output a Base64 encoded
Before we move on, let's export a path we will use later
Next we want to create an endpoint which we can send our images to for processing and which uses
our new functions. Create a new folder in the project at
src/routes/api and within the new directory add a
and add this content:
Our endpoint can process multiple images in a single request. We feed in file names in an
images array, it looks for these files in the
src/lib/assets folder. Once
again we are using promises. If you looked at promises for the first time in the code block above,
you might want to gloss over the details here as this is next level promises.
13 we are using
Array.map() to go through each element of the provided array of
images and map
the elements to a new output array;
dominantColourPromises. So the
first element of
images corresponds to the first element of
dominantColourPromises and so on. You might remember that
async function which means it returns a promise. As a consequence,
in the last line of the map function (line
15), when we return the
result of the call to
dominantColourPlaceholder, we are actually
adding a promise to the the output array, rather than the result.
dominantColourPromises is in fact an array of promises (the name should make sense now).
promise in the first element
dominantColourPromises to resolve before
we start processing the second. We can start them running immediately one after the other. This is
convenient here as there is no link between the dominant colour of one image and the next. We just
need to make sure all of the promises are resolved before we return the entire array. That is what
the code in line
23 does. It takes the input array of promises and
once they have all resolved, generates an output array of the results. As a warning, this works fine
Array.map(), though if we needed to use
Array.forEach() instead (and some other array methods), we would have to handle promises differently.
For our example we will pass in an array containing a single image, though the code can handle
multiple images efficiently. The endpoint responds with an object containing two arrays:
dominantColours. These both map to the input
image array and are returned in line
26. Speaking of which let's next
call the endpoint from our home page Svelte file.
We can easily generate images in multiple formats and sizes using the
vite-imagetools plugin. However for generating our placeholders we will use our endpoint. In theory you can create
a low-resolution placeholder with
vite-imagetools by just setting image
width to 10 pixels in the query string. However, we have created functions, so that you can see how
to do it yourself. On top that trick wouldn't generate a dominant colour placeholder.
Next in our load function we will call the new endpoint to pull in the placeholders. Following
that, we will generate the responsive images using
vite-imagetools. Finally we set the placeholders to display initially and until the actual image loads.
First update the load function in
15 we can give all the images we want to generate placeholders
for. For our case, it is just the one. In line
27 we make the placeholder
available in the following
Let's generate the responsive images now, using
the main script block:
As before, we use query parameters to tell
vite-imagetools what to generate. Here we generate
srcset which is needed to create a responsive image. The
srcset is just
there to tell the browser what image sizes are available. In our case we have three image widths which
are double width, for retina displays, 672 pixel wide (for desktop) and half-width, for mobile.
You can add more, depending on common display widths used by your site visitors. In the two highlighted
srcset attributes for WebP and JPEG which
we can use in a
picture element on our page. Check the
vite-imagetools documentation for a full list of available query parameters .
Let's wrap our
img element in a
picture element and add
the responsive images. We also define
sizes in the last line of the script block. This
serves as a guide to browsers to choose the right responsive image source based on display width. The
syntax is similar to the CSS media query syntax. Essentially here we tell the browser that the image width will be equal to the viewport width
less our margin. This is in the case that the viewport is smaller than 672 pixels wide. Otherwise
the image is 672 pixels wide. The information is handy because it lets the browser download the
right images while it is still working out the layout.
Here we add the
srcset attributes, specifying the WebP image first,
then the JPEG. The order is important here. The browser tries the sources in the order they appear.
If it does not support WebP, it tries the next source which is JPEG and settles for that as a fallback.
If you included AVIF and JPEG XL too, since JPEG XL is new and enjoys less support than AVIF and WebP
the order would be JPEG XL, AVIF, then WebP and finally JPEG as a fallback.
Take a look at the page in your browser and right-click and save the image. If you have WebP support in your browser you should see it saves a WebP format image. The final piece missing is the placeholders. Let's get those in and wrap up.
We will use
vanilla-lazyload to do the heavy lifting with lazy loading.
It makes use of the Intersection Observer API so the browser shows placeholders until the image is within the visible viewport. You will still
see the blur-up effect as the image loads.
every page with lazy loading content. On most sites, this would be every page so we can place the
code in the layout component. Edit
src/routes/__layout.svelte to import
the plugin and then create an instance if one does not yet exist:
browser is a boolean which is true when code is running in the browser
as opposed to on the SvelteKit server. This is needed here because accessing the
document object on the server would throw an error.
Let's return to the home page code and finish things off. We need to import the
placeholders props which we created in the load function. We
also need to tell our lazyload code to update when the pages loads:
Now when the pages loads,
vanilla-lazyload will look for
img elements with the
lazy class (it also works on iframes, as you can see in this short video). Initially we want to show the placeholder image so, we set out
src to the placeholder image. Although we are working
with Base64 images encoded in a string, instead of a path to an image file we can use the
src attribute in exactly the same way.
vanilla-lazyload determines when
it is time to load the final image, replacing the placeholder. For it to know what the final attribute
should be, we tweak the code slightly, so where we would have
src normally, we use
vanilla-lazyload swaps these out for the right content when it
is time to load the image. Let's update the picture element:
If you hit refresh on the page, you should see the dominant colour flash and then the actual
image. Inspect the
picture element in your browser. You will see the
plugin has worked its magic and the
data-src attributes match. Similarly, it will have added
Next lets replace
placeholders in line
139. Remember we returned an array of placeholders,
since we want the first element in that array (of just one image in our case), we use index
If your image looks a little grainy on the dev server, I noticed this too. However when I pushed to a live server and published the demo site for this post it looked fine.
It could get tiresome including all the boilerplate code on every image of our site. As an
alternative, you might consider wrapping up some of the functionality into a component. There is
Image component which does exactly this in
You can see docs on the component's Git Hub page .
🙌🏽 SvelteKit Image Plugin: Wrapup
In this post we:
had an introduction to
- saw how to generate dominant colour as well as low resolution placeholders using the sharp image processing plugin,
- learned how to add cached, Next-Gen, responsive images with no cumulative layout shift using a SvelteKit image plugin.
You can see the full code for this tutorial on the Rodney Lab GitHub page . There is also a demo site .
I really do hope you found this SvelteKit Image plugin article useful. You will note we included a static import of the image file in the page Svelte code. This will be perfect for a lot of situations. Where you render a page using a template, and the image included is different for each invocation of the template (for example the banner image in a blog post), you will need to use a dynamic import. That way you can pull in the right image for each page at build time, without having to include all possible images in the template. We will look at how to do this in this post dedicated to SvelteKit dynamic image import.
- There is currently no built-in image plugin which automatically generates next-generation copies of image in responsive sizes. However SvelteKit uses vite tooling and the vite-imagetools plugin is fantastic. You can use the plugin to generate images in the next-gen formats and responsive sizes you want. The plugin takes care of hashing the images so that vite can cache them. To generate the images, you just import the original JPEG or PNG file in a Svelte component with a special query string on the end. The query string details the image formats you want vite-imagetools to generates together with output image sizes. As well as the images themselves, you can get metadata such as input height and width by tweaking the query string. Although vite-imagetools generates all the images you need for responsive images, you still need to add the responsive markup yourself. This lets you choose low resolution placeholders and add lazy loading.
- You can easily add lazy loading images in SvelteKit using the vanilla-lazyload package. Lazy loading images are ones which do not load initially, but rather just before they are scrolled into view. The advantage of implementing lazy lading is that the browser can focus on loading visible content quicker, improving user experience. To make an image lazy load using the plugin, just add the lazy class. You can also add low-resolution placeholders for your images using vanilla-lazyload. Doing so means the page content will not shift as the images load (known as cumulative layout shift). This is another user experience quick win.
- Responsive images are the set of images your server can make available for different screen formats. For your images to look sharp on Retina displays, you need to provide an image, double the width it will be displayed at. This can be quite large of you want to cater for large desktop screens. That same image on a small mobile screen will be far larger that needed. If the user has a slow internet connection or limited data, you end up degrading user experience with a far larger image than needed. By making smaller images available and adding some markup to your images, you can let the user browser know what image sizes are available and let it choose the best one for its own display size.
- The idea behind next-gen images to preserve the image quality while offering smaller image file sizes. This can mean users download images quicker and get a better user experience. JPEG and PNG are more traditional formats. WebP images can be used to encode either, typically the image is degraded slightly but much smaller than the original. AVIF is a newer, next-gen format offering improvements on WebP compression. WebP currently enjoys wider support that AVIF so serving fallback alternatives is best practice. The browser can iterate through the alternatives you supply until it finds one it can work with. The latest format is JPEG XL, this looks like a promising replacement as the standard, the support needs to grow a little before it can get there.
Have you found the post useful? Which other hosting service would you like to know how to host a SvelteKit site on? Would you like to see posts on another topic instead? Get in touch with ideas for new posts. Also if you like my writing style, get in touch if I can write some posts for your company site on a consultancy basis. Read on to find ways to get in touch, further below. If you want to support posts similar to this one and can spare a few dollars, euros or pounds, please consider supporting me through Buy me a Coffee.
Finally, feel free to share the post on your social media accounts for all your followers who will find it useful. As well as leaving a comment below, you can get in touch via @askRodney on Twitter and also askRodney on Telegram . Also, see further ways to get in touch with Rodney Lab. I post regularly on SvelteKit as well as other topics. Also subscribe to the newsletter to keep up-to-date with our latest projects.