Performance: Responsive images
Responsive images affect page load speed by delivering appropriately sized images for different screen sizes, reducing data usage and improving rendering time.
Jump into concepts and practice - no test required
<img srcset="small.jpg 480w, medium.jpg 800w, large.jpg 1200w" sizes="(max-width: 600px) 480px, (max-width: 900px) 800px, 1200px" src="large-image.jpg" alt="Example image">
<img src="large-image.jpg" alt="Example image">
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Single large image for all devices | Minimal | 1 reflow on load | High paint cost due to large decode | [X] Bad |
| Responsive images with srcset and sizes | Minimal | 1 reflow on load | Lower paint cost due to smaller images | [OK] Good |
srcset and sizes attributes in an <img> tag?srcset and sizessrcset attribute lists multiple image files with different sizes or resolutions. The sizes attribute tells the browser how large the image will appear on the screen.srcset and sizes?srcset attribute formatsizes attribute logic(max-width: 600px) to specify image display size. <img srcset="small.jpg 500w, large.jpg 1000w" sizes="(max-width: 600px) 500px, 1000px" src="large.jpg" alt="Example"> correctly uses this to tell the browser when to use which image size.<img srcset="small.jpg 400w, medium.jpg 800w, large.jpg 1200w" sizes="(max-width: 600px) 400px, 800px" src="large.jpg" alt="Sample Image">
<img srcset="image-400.jpg 400w, image-800.jpg 800w" sizes="(max-width: 600px) 800px, 400px" src="image-800.jpg" alt="Error Example">
srcset. Which of the following is the best way to write this for an image named photo.jpg?