Published on

How to Optimize Your Images for Free with wsrv.nl CDN

Authors

Images are essential part of any website. It helps us to understand the content better. Without it, we might feel the site is boring.

However, having an unoptimized images can result in significantly affect the performance of our website. And make our site load so slowly.

There are lots of ways to optimize the images like compressing it using tools like ImageOptim, using CDN to deliver the images efficiently.

In this article, let's see how to optimize the image using wsrv.nl

Why wsrv.nl?

  • It's open source
  • And it's free. You don't even have to create an account to use them.
  • Uses CloudFlare's infrastructure under the hood.
  • You can resize, crop, change it's quality, control the cache, etc using a simple API.

How to use it?

You just need to pass your image as url query string to https://wsrv.nl/ and that will take care of the rest.

For example:

We've an image https://upload.wikimedia.org/wikipedia/commons/3/3a/Logotest123.jpg that we want to use it in our website.

Instead of directly using it in our website. We can use it via wsrv and get all the benefits like this:

https://wsrv.nl/?url=https://upload.wikimedia.org/wikipedia/commons/3/3a/Logotest123.jpg

When someone views it for the first time, it'll be cached. And from then on it'll be served from the cache.

Code Snippet

Here is a code snippet to help you to easily generate the wsrv.nl CDN URL. It is based on kikobeats snippet.

const imageUrl = (url, opts) =>
  `https://wsrv.nl/?${new URLSearchParams({
    
    /* The image URL to optimize */
    url,
    
    /* In case something goes wrong, just show the image */
    default: url,
    
    /* 
      Compress it as much as possible (PNG).
      See: https://images.weserv.nl/docs/format.html#compression-level 
    */
    l: 9,
    
    /* 
      Reduce PNG file size.
      See: https://images.weserv.nl/docs/format.html#adaptive-filter
    */
    af: '',
    
    /*
      Enable image optimization for GIF and JPEG.
      See: https://images.weserv.nl/docs/format.html#interlace-progressive
    */
    il: '',
    
    /*
      Enable image optimization for WebP and GIF.
      See: https://images.weserv.nl/docs/format.html#number-of-pages
    */
    n: -1,

    /* 
      Pass any other option.
      See https://images.weserv.nl/docs/quick-reference.html 
      
      It's recommended to pass `w` for cutting down the image size.
    */
    ...opts
  }).toString()}`

Happy optimized images!