htmlcssimagepage-load-time

html load background image lower quality


I have a website with the code:

#part1{
    background-image: url('grass_v001.png');
}

However, the grass_v001.png is a very large file, and takes several too many seconds to load on the browser (slow load times = a less professional look). Is there a way to lower the quality of the image solely through css? I'd rather not work in JS or Jquery for this, but I will if I need to. Thanks!


Solution

  • For CSS, you can use image-set to deal with this.

    Create a few smaller sized versions of your image, and provide them in the image set - then let the browser pick the appropriate one. This way, larger screens that can make good use of the higher resolution will get served that, and smaller screens can use the faster, lower resolution image.

    The image-set() CSS functional notation is a method of letting the browser pick the most appropriate CSS image from a given set, primarily for high pixel density screens.

    Resolution and bandwidth differ by device and network access. The image-set() function delivers the most appropriate image resolution for a user's device, providing a set of image options — each with an associated resolution declaration — from which the browser picks the most appropriate for the device and settings. Resolution can be used as a proxy for filesize — a user agent on a slow mobile connection with a high-resolution screen may prefer to receive lower-resolution images rather than waiting for a higher resolution image to load.

    image-set() allows the author to provide options rather than determining what each individual user needs.

    Example

    #part1 {
        background-image: image-set(
            url('grass_v001_small.png') 1x,
            url('grass_v001_large.png') 2x
        );    
    }
    

    You'll want to also add a duplicate '-webkit-' vendor prefix for some browsers (you should consider CSS processors to handle this for you).

    #part1 {
            background-image: image-set(
                url('grass_v001_small.png') 1x,
                url('grass_v001_large.png') 2x
            );
            background-image: -webkit-image-set(
                url('grass_v001_small.png') 1x,
                url('grass_v001_large.png') 2x
            );    
        }