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" />
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 theimg
<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
).
- 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.
Top comments (0)