1

The website GTmetrix is giving me low score on "Optimize images" for the following reason:

On my main page I have 4 columns with images. Each column takes 25% of the screen resolution so on my 1920x1080px monitor, each image has width of 463px. However, when the user is viewing the main page on a device with resolution between 600px and 1200px, I only show 2 columns instead of 4 which makes the images bigger in width compared to when I have 4 columns (when close to 1200px). When I'm displaying 2 images on 1199px browser width, each image has width of 576px. Now here lies the problem.

If I were to use 576px natural image size, GTmetrix would say "Optimize the following images to reduce their size by X" because I'd be using 576px width natural image but when I have 4 columns, the max size I'd need is 463px.

If I were to have the natural image in 463px, the images that are displayed when using 2 columns would be streched to 576px which will reduce the quality.

Now I can't figure out how to satisfy both sides.

2

The best way to optimize page performance yet serve high-res images to high-dpi clients is to use the img srcset HTML attribute, like this:

<img
 srcset="
  /img/image4x.jpg 4x,
  /img/image3x.jpg 3x,
  /img/image2x.jpg 2x,
  /img/image1x.jpg 1x"
 src="/img/image1x.jpg"
>

In this example, the larger multipliers link to images that are 2x, 3x, and 4x as big as the default size. Modern browsers are smart enough to automatically pick the larger image if they are running on a high-dpi display.

You can even use the sizes attribute to hint to the browser which image is best for different screen sizes.

More info:

  1. https://html.com/attributes/img-srcset/
  2. https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.