[CSS] Serve optimized images

发布时间 2023-07-20 00:37:18作者: Zhentiw

Try throttling to a slow internet in the browser Dev tools and visit a website made up of HD images like unsplash. That's how to experience the pain of your website visitors trying to enjoy your high HD content from geographical areas with slow internet.

But you can provide a rescue especially with the image-set CSS trick.

You can give options to a browser to let it decide the most appropriate image that suits a user's device. For instance:

.banner {
    background-image: url("elephant.png"),
    background-image: -webkit-image-set(
        url("elephant.webp") type("image/webp") 1x,
        url("elephantHD.webp") type("image/webp") 2x,
        url("elephant.png") type("image/png") 1x,
        url("elephantHD.png") type("image/png") 2x
    );
}

The code above will set the background image of an element.

If -webkit-image-set is supported, then background image will be an optimized image, i.e an image of supported MIME type and that better suits the resolution power of the user's device.

For example: Since a higher quality image is directly proportional to a larger size, a user who has a high resolution device but in a poor network, will prompt the browser to decide on serving a supported image with lower resolution. Ii is logical not to make a user wait for the HD image to load.

 

Read more: https://dev.to/smitterhane/13-css-tricks-that-will-give-you-an-adrenaline-rush-5908