DEV Community

Cover image for Optimize images for website
Dominik Ilnicki
Dominik Ilnicki

Posted on • Edited on

29 4

Optimize images for website

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');
 }
} 
Enter fullscreen mode Exit fullscreen mode

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.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools can’t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay