💻 7 Must-Know Tips for Responsive Images to Boost Your Site Score 🚀
Tags: webdev, programming, beginners, html
Published: 2023-11-09 15:35:10

We all use images on our websites, whether a hero image, our logo, or an icon on buttons and links. Using images and graphics is important, but we must be aware of some pitfalls when incorporating images into our websites.

Here's a list of must-know tips when using images in our code. It is not a comprehensive list, but a good starting point.

Let's jump right in.

### **🖼️ Choose the appropriate image type**  
When adding an image to a page, picking the appropriate type of image is essential. While no strict rules apply, here are some practical guidelines for choosing the proper image format:

* Choose SVG format for logos, icons, decorations, or simple graphics. Its vector properties allow you to scale it up without damaging its quality, and its size is smaller than raster image formats like JPEG and PNG. It can also be manipulated and animated via CSS and JS and embedded directly into HTML documents.

* GIF and WebP are the most popular choices for animated images (APNG is also a [good pick](https://caniuse.com/apng)).

* Use WebP, AVIF, JPEG, or PNG for complex images and real-world photos. They are widely supported, have excellent compression algorithms, and support "alpha channel" transparency.

### **🖥️ Display different images according to screen size and resolution**  
Displaying a wide image on a page looks fine on desktop screens but might look too cramped when viewed on mobile screens.

<figure>
![Same picture looks good on desktop but looks cramped on mobile screen](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3a3ys9p26yx7m10dtp90.jpg)
<figcaption>Demo non-responsive website <a href="https://mdn.github.io/learning-area/html/multimedia-and-embedding/responsive-images/not-responsive.html">by Mozilla</a></figcaption>
</figure>

Instead of providing a single image to all screen sizes, leverage the `srcset` and `sizes` attributes to offer multiple image sources and let the browser pick the most suitable one based on the user's device, screen size, and resolution.

<figure>
![Different pictures on desktop and mobile looks good on both screens](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oyu4x2j3ntk76idplx1d.jpg)
<figcaption>Demo responsive website <a href="https://mdn.github.io/learning-area/html/multimedia-and-embedding/responsive-images/responsive.html">by Mozilla</a></figcaption>
</figure>

### **🤌 Improve page load time by deferring image loading**  
Largest Contentful Paint (LCP) is a Core Web Vital performance metric. It measures the time it takes for the browser to render the most prominent content element (e.g., image, text block) visible within the viewport. When a page loads, all the content is downloaded and parsed, regardless of whether it's visible in the viewport. Images block the page render, so we want to delay image loading as late as possible.  
A recommended best practice is to delay the loading of images that are not immediately visible to the user by setting the `loading` attribute of those images to `lazy`.

```html
<img src="image.jpg" loading="lazy" alt="..." />
```

### **😵‍💫 Set `width` and `height` for images to avoid Cumulative Layout Shift**  
Cumulative Layout Shift (CLS) occurs when a page's content unexpectedly shifts due to dynamically added elements. This issue is often triggered by images or videos with unknown dimensions. After being loaded, these elements are inserted into the page, causing other elements around them to move to accommodate them.  
To mitigate this issue and ensure a smoother user experience, set the `width` and `height` attributes on `img` tags to inform the browser ahead of time how much space it needs to reserve for each image.

```html
<img src="image.jpg" width="640" height="360" alt="..." />
```

### **📟 Support old browsers by providing a fallback format**  
WebP and AVIF image formats are efficient and lightweight, making them excellent choices for web usage. However, they are [not fully supported](https://caniuse.com/avif) in all major browsers yet (WebP has better support than AVIF and JPEG XL).  
Employ the `picture` and `source` tags to serve these formats to compatible browsers, and include an `img` tag with a more universally supported format as a fallback for older browsers.

```html
<picture>
  <source type="image/webp" src="image.webp" /> <!-- Supported by browsers with WebP format compatibility -->
  <img src="image.jpg" alt="..."> <!-- Default fallback format for older browsers -->
</picture>
```

### **🦾 Utilize build tools to prepare your images for production**  
Incorporate build tools into your development workflow to automate image optimization for production. Optimizing your images ensures optimal rendering on various devices and saves user bandwidth.  
There are variety of responsive image plugins like [gulp-responsive](https://www.npmjs.com/package/gulp-responsive) for Gulp, [image-minimizer-webpack-plugin](https://www.npmjs.com/package/image-minimizer-webpack-plugin) for Webpack, or [vite-imagetools](https://www.npmjs.com/package/vite-imagetools) for Vite.

### **💯 Verify best practices for images on your page**  
Proper usage of images on the web involves selecting image format, responsive design, and accessibility. Regularly audit your web pages to confirm you are following the best practices and providing users with a seamless experience.
After following the tips above, use a tool like [Lighthouse](https://developer.chrome.com/docs/lighthouse/overview/) or [RespImageLint](https://github.com/ausi/RespImageLint) to test your pages for best practices. They give you insights about your page's performance and tips for improving it.

### **🔍 Bonus Tip: Set `Cache-Control` headers for your local images**  
When serving images from your server, set the `Cache-Control` header for your images. It'll save your users' bandwidth, reduce load on your server, and improve your site's loading time.

A good practice is to hash your image file names and set their `Cache-Control` header as follows:

```http
Cache-Control: max-age=31536000, immutable
```

To learn more about caching your images and other assets check out my articles [about caching](https://dev.to/yishai_zehavi/http-caching-explained-part-1-theory-3j4m) and [how to implement caching strategies in your code](https://dev.to/yishai_zehavi/http-caching-explained-part-2-implementation-4ppa).

---

Implementing these seven tips in your code can significantly benefit your user's experience and your site's performance. Comment below if you have more tips and tricks you want to share.

Thanks for reading. See you in the next article! ✍️👋🏼