Mastodon

Optimising images in a website

Mar 12, 2019 by Kolappan N

Images are a huge part of a website which consumes a large chunk of bandwidth for a site. Larger images can significantly slow down a site. Hence optimizing image is a key part in site speed up. Image optimization is not just about compressing images. There is much more to it. Infact I will say that compressing images is not as important as you think.

1. Choosing the right format

There are many image formats out there. Choosing the right format for the right image will reduce the size required. Here are some points about popular image formats,

2. Image size

Have various sizes of your image and serve low size images for mobile devices. Instead of serving a larger image and resizing it in a browser, send a smaller image instead. Reducing an image size will reduce the file size.

3. Adapt for device & networks

Code your server to adapt for your client device. Some of the examples are,

save-data header in chrome: When detected you can server low-resolution images to reduce data usage. accept header: You can also choose the image format dynamically while serving based on this. For example, you can use the accept header to check for WebP support and serve WebP images if supported. navigator.connection.downlink: This can be used to detect network speed.

4. Cache images

This is one of the essential steps that will make your website load faster for repeated visits. Always set a cache header for images. I would normally cache for 30 days. This reduces bandwidth consumption and loads the site faster.

5. Compression

This is the first thing that will come to your mind when speaking about image optimization. When compressing images it is best to use lossless or zero perpetual algorithms that compress images without quality loss. You can also automate this process with bots, build scripts, etc… I use ImgBot on GitHub to losslessly optimize all images in my repos.

6. Lazy loading

This is a method where the image that is visible at first aka below fold images are loaded at the very last in the background so that the initial view area of the page is rendered fastly. You can also use HTTP push to send some frequently used images before they are requested by the browser. An example would be to push a cart icon in the login screen of an e-commerce website.

7. Use CSS if possible

Some of us use an image to provide styles to the background, etc… If those styles can be achieved using CSS then use CSS instead.

8. Avoid duplicate images

While this seems pretty basic, many people still do this. I have seen sites where two images are using the same icon of a different colour. Why not use an SVG image and colour it using CSS?

Credits

This article is based on the presentation by Aditya Patadia on LinkedIn Site Speedup Meetup organised in Bengaluru, India.