Including WebP Images for Various Screen Sizes and Densities

By Forrest Smith - Drempd.com

I've been working on optimizing images on a site of mine, and ended up really digging into the images necessary to be optimized at various monitor pixel densities, along with images based on screen width. This also ended up requiring a bit of a process to generate all of the necessary images.

The first line specifies what to use on mobile (widths of less than 500px). In a lot of cases, I'll just save the image at 500px, and I'll set it to display at 100% wide when the browser window is less than 500px wide. However, Lighthouse always throws a notice that the image isn't sized optimally, which is technically true -- on whatever device size it's being tested at, it will be scaled down from that 500px. Normally I can live this for the better user experience of having a full width image, but for my current client, this is an issue, so my strategy is to size the image at 360px for all devices less than 500px, and just center align the image.

If we're greater than 500px, the second line is used, and I've specified an image for normal pixel densities, and one for higher pixel density displays.

The third line gets used if webp format isn't supported for simplicity, I could just use a single jpg size here, but in thinking of my overall process for this, it makes sense to create the jpg @2x, and then just generate all of the images from that, so I might as well include it here as well.

The final line is used if the 'picture' tag isn't used, and also for including the alt tags, style. Basically what ever image is selected from the list is inserted there in the src parameter.

<picture>

    <source media="(max-width:500px)" srcset="image-360.webp 1x, image-360@2x.webp 2x">   

    <source type="image/webp" srcset="image.webp 1x, image@2x.webp 2x">

    <source type="image/jpeg" srcset="image.jpg, image@2x.jpg 2x">

    <img src="image.jpg" alt="something" style="margin: 0 auto;">

</picture>




So that I think makes for a fairly robust and optimized solution. Of course now I need to have all of the images -- all 6 of them.   I'll need:





  • image-360.webp


  • image-360@2x.webp


  • image.webp


  • image@2x.webp


  • image.jpg


  • image@2x.jpg






My strategy is to only generate a single jpg image from whatever software I'm using (affinity designer or photoshop for me), and then create some system to automatically generate the other ones from that image.