Home > Blockchain >  Should the browser download multiple images when using srcset?
Should the browser download multiple images when using srcset?

Time:07-02

my html markup is as follows:

<img srcset="https://res.cloudinary.com/xxx/image/upload/c_scale,w_300/v1653408278/notforsquares/ll/DSCF4429.jpg 300w, https://res.cloudinary.com/makingthings/image/upload/c_scale,w_600/v1653408278/notforsquares/ll/DSCF4429.jpg 600w" sizes="(min-width:300px) 50vw 100vw" src="https://res.cloudinary.com/makingthings/image/upload/v1653408278/notforsquares/ll/DSCF4429.jpg" alt="Lamp" />

When I look at the network tab in the inspector it shows two images downloaded. Is that the correct behaviour?

enter image description here

Thanks in advance

CodePudding user response:

Yes, if you open it on a wide-screen device, it will load only one image like the example below:

enter image description here

Otherwise, if you open it in small-screen device, it will load only both image like the example below:

enter image description here

this is the code he use to implement the elva-fairy image:

<img srcset="elva-fairy-480w.jpg 480w,
                     elva-fairy-800w.jpg 800w" sizes="(max-width: 600px) 480px,
                    800px" src="elva-fairy-800w.jpg" alt="Elva dressed as a fairy">

Link to the web: https://mdn.github.io/learning-area/html/multimedia-and-embedding/responsive-images/responsive.html

You can use the picture tag if you want to load it only once based on screen size:

<picture>
          <source media="(max-width: 799px)" srcset="elva-480w-close-portrait.jpg">
          <source media="(min-width: 800px)" srcset="elva-800w.jpg">
          <img src="elva-800w.jpg" alt="Chris standing up holding his daughter Elva">
</picture>

CodePudding user response:

Yes, this is the correct behaviour. By using srcset you're basically setting all the possible image sources the browser can use (and their sizes). You should also use sizes attribute to indicate which image (and it's size) the browser should use on different breakpoints.

  •  Tags:  
  • html
  • Related