Responsiveness has been a key quality feature of modern websites for a few years now. This includes first and foremost the ability to scale a website or web app to different screen sizes, including the images. Behind the scenes there is more that can be optimized. HTML5 allows for using different images depending on the visible image area using the srcset and sizes attributes on the img tag or using source tags with different media conditions inside the picture tag. This allows us to load smaller images on smaller screens, for instance on mobile devices, and save a considerable amount of bandwidth. Therefore, it’s not only a question of nice looks, but of performance as well. Checkout the MDN page about responsive images for details.
When talking about responsive images we usually talk about the same image in different resolutions. Of course, those images need to be created and there are three ways (out of the back of my head) that we can use to generate these images.
- Don’t! Simply use vector images like Scalable Vector Graphics(SVG). These images automatically scale, are usually considerably small and look good in any resolution. That is not an option for complex images like photos.
- Images of that kind can be pre-generated and loaded onto the server together with the website. That means generating all resolution variants of all images before putting the website on the server. This can take a lot of build time depending on the amount of images and maybe not all the images will ever be requested. Nevertheless, this is the solution for completely statically served websites.
- The alternative for option 2 is to create the scaled images when they are requested. Here we only load the full image onto the server together with the website / web app. When the browser requests the image in a different resolution, then the server application will generate the image in the other resolution from the full scale image and return that. This requires a web server application that can generate the images at runtime. However, it is not necessary to create the images before letting the website / web app go live and only those images will be created that are actually requested by a browser or other client.
None of the above-mentioned concepts are new, but we are going to take a look on how to implement option 3 using NestJS and the image conversion module sharp.