Performant responsive Images for all resolutions

folder_openBlog, Webentwicklung
commentKeine Kommentare

Mobile First is really 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.

[ultimate_heading main_heading=”THE GOOD OLD” alignment=”left” margin_design_tab_text=””][/ultimate_heading]

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 too big.

Anzeige
.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.
[ultimate_heading main_heading=”HERE IS THE SOLUTION” alignment=”left” margin_design_tab_text=””][/ultimate_heading]

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 lazy-loading way

Add the library 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 closing 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 media="--mobile" data-srcset="images/small/image-123.jpg" />
    <source media="--desktop" data-srcset="images/big/image-123.jpg" />
    <img class="lazyload" alt="title" data-src="default-image.jpg" />
</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!

Related Posts

Kommentar verfassen

Menü