loading...
Cover image for Optimize images for website

Optimize images for website

dominikilnicki profile image Dominik Ilnicki Updated on ・2 min read

Unoptimized images may cause a lot of performance issues and slow down your site significantly. In this article, I'll share with you some ways how to increase your web app performance dealing with images.

01. Lazy loading

Lazy loaded images start loading only when they are in the user's viewport. That's a huge win because you don't need to load all the images at once.

how to do it?

The simplest way is to use native HTML loading attribute and set it to lazy on the img element

<img src="../assets/photo.jpg" loading="lazy" />

check the browser support

02. Load proper images sizes

In the perfect world, you should never load a bigger image then you display, it's just a waste of transfer. You can define which image needs to be load depend on the user's screen resolution. There are a couple of ways to achieve that.

  • Set srcset on the img

<img src="images/photo.jpg" srcset="images/photo_medium.jpg 100w,images/photo_large.jpg 400w"/>

In that attribute, you can tell the browser that you have the same image in different sizes by providing a path to the asset and intrinsic width in pixels (100w).

read more on MDN

  • Use media queries

In some cases you can't use srcset property because you don't use the img tag. For example when you set the background image. The solution is simple, you can define different background images using media queries.

example:

@media (max-width:1280px){
 hero-wrapper{
  background-image: url('assets/hero_medium.jpg');
 }
}
@media (max-width:720px){
 hero-wrapper{
  background-image: url('assets/hero_small.jpg');
 }
} 

03. Use compressed images

According to the Google Chrome Developers team most of your images should have less than 100kb.
You should consider using jpeg or webp formats. They are way lighter then png files. You can use squoosh the tool maintained by Google that allows you to convert and compress your images.

03. Images optimization CDNs

There are some tools that compress, resize, and make other transformations on your photo to reduce loading time. I personally use imagekit and it does the job very well.

Posted on May 25 by:

dominikilnicki profile

Dominik Ilnicki

@dominikilnicki

Building justcontribute.netlify.app / Learning frontend

Discussion

markdown guide