mercredi 1 septembre 2021

How does the browser determine which srcset image to load when no sizes attribute is present?

I have an image that gets displayed in various sizes on my website:

  • The website is responsive and the apparent image size is often the size of the browser, with some exceptions when the browser is very wide. So, the image's width can vary between 200 and over 1000 pixels.
  • We want the image to be displayed in native resolution on high-resolution devices (Retina).

So, our image is present in three resolutions, let's call them i1.png, i2.png and i3.png.

What I would like to do is just this:

<img src="i1.png" srcset="i1.png 420w, i2.png 840w, i3.png 1260w" />

In my opinion, the browser should have enough information to figure out which image it needs.

  • On a standard-resolution device (no retina screen), it just takes the width of the <img /> element and then loads the image that has a width higher or equal to the width of the element. E.g. if the image element is 600px wide, then it will load i2.png.
  • On a retina device, it would just multiply the width of the <img /> element with the device-pixel ratio. E.g. on a "2x" device, it would load i3.png for a 600px image, because 2 x 600 = 1200, so it would need the image with a width of 1260px.

It seems the browser indeed does something like that, but in some cases it would load the 840px image even though the 420px image would be enough.

What factors does the browser use to determine the size of the image to load?

  • Is it using CSS rules to determine the image's apparent width?
  • Or does it ignore CSS and just look at width and height attributes on the <img />, if present?
  • What if some parts of CSS are not yet loaded?

Crucial point: I do not want to use the sizes attribute, because I would need media queries for all possible combinations of device-pixel ratios and browser window widths. This should not be necessary, because as I said, the browser should have enough information.

I checked the Mozilla Docs about the topic, but they say that if sizes is omitted, then we need to use 2x descriptors (instead of 420w descriptors) in the srcset attribute. This is useless for my scenario: the goal is to have the browser find out which image to load, not just based on device-pixel ratio, but also based on responsiveness.




Aucun commentaire:

Enregistrer un commentaire