Performant responsive Images
Image by joshborup @ pixabay

Performant responsive Images for all resolutions

Mobile First is omnipresent. We all keep in mind the google fokus on mobile devices as ranking index. Also important is the time to load a page. This is a ranking factor. With this background, we need to think about a good solution to display images specific for the relevant device.

The good old

In the past developer often use background images to fill a container with an image and change the background-size in the different media query like this:

.my-image {
    background: url('url-to-image.jpg');
    background-size: cover;
}

Another option is to set the image width to 100% and set the height automatically depending the image width. This can be alternate, but sometimes images can get artefacts if the size is to big.

.img {
    width: 100%;
    height: auto;
}

But in both options you didn’t have different images and image-quality depending of your screen resolution. It make sense to get images in different sizes and qualities to server the best load-performance for each device.

Always think about smarthphone users!

It's a very bad idea to insert an 500kb image greater than 1000px on a mobile device. Be aware - mobile users will slap you!

Imagine - you sitting i a subway and want to read a nice website like yours. On every page you need to wait for download images with a lot of megabytes. That's frustrating.

Here is the solution

Load different images for mobile and desktop users is simply easy. In this case i recommend to use NPM Packages - lazysizes. This smart lib loads your images in a cool lazyloading way

Add the libruary to your project.

Include these files in your project js. You can easy use Gulp, Grunt or Webpack for this. This asset files & media query-js needs to insert before your closeing head </head>.

    node_modules/lazysizes/plugins/bgset/ls.bgset.js
    node_modules/lazysizes/lazysizes.js
    window.lazySizesConfig = window.lazySizesConfig || {};
    window.lazySizesConfig.customMedia = {
        '--mobile':       '(max-width: 768px)',
        '--desktop':      '(min-width: 769px)'
    };
<picture>
    <source data-srcset="images/small/image-123.jpg" media="--mobile" />
    <source data-srcset="images/big/image-123.jpg" media="--desktop" />
    <img class="lazyload" data-src="default-image.jpg" alt="title" />
</picture>

Now you can easy load different images for each media-query or device type. I prefer only 2 media query. So i can be sure the tablet device is always included. In portrait the mobile media query will be load and in landscape the desktop viewport is applied.

Hope it helps you a lot.
Thanks!