L o a d i n g

How to increase your website speed by optimizing images

An image speaks a million words but may also cost a million seconds to load when not properly optimized. Slow websites will frustrate your visitors and make them leave before they even see what's on your website simply because an image couldn't load. In this post, I'm going to show you how you can optimize your images and hopefully make your site load faster.

Compress your images

This is probably the first thing you are going to want to do. Make sure you compress your images to the least size possible without sacrificing the quality. Use tools like Imagick or online tools like Compressnow before using those images on your site.

Inline the images

The other way you can reduce the impact of images is to load them inline as base64 encoded data-uri. This way your images are loaded as soon as the initial HTML is loaded. However, this may increase the response payload size but the reward is worth it especially if they are background images.

Using a CDN

A CDN will cache your images by storing copies in multiple servers around the world. Additionally, with services like Cloudinary you get real-time image transformation by just manipulating the URL parameters. This allows you to serve different image sizes for different screens. To learn more about how you can benefit from a CDN read this article

Lazyloading

Lazy loading is a technique of loading an image only when it is needed or when it is in the viewport. I'm going to show you can do this with lazysizes js a javascript library for lazyloading. One thing to note is that lazyloading is natively supported in Chrome by just passing the loading="lazy" attribute to the image.

To install this library run

npm install lazysizes

Then in your javascript just

import 'lazysizes'

We are going to use Low-Quality Image Placeholders then replace the original image when it is loaded. You may have seen this in action on Medium.

In your HTML

<img src="path-to-your-very-low-quality-placeholder-image' data-src="path-to-image"  class="lazyload">

The class="lazyload" tells lazysizes js that we want that image to be lazy loaded the data-src tells it that we want to use a placeholder before the real image can be loaded.

Let's some styling to make the placeholder blurry

.blur-up {
    -webkit-filter: blur(10px);
    filter: blur(10px);
    transition: filter 400ms, -webkit-filter 400ms;
o}

.blur-up.lazyloaded {
    -webkit-filter: blur(0);
    filter: blur(0);
}

And we're done, you now a fast website with images lazyloaded. To learn more about you can improve your website performance read this article on the Shopify Partner Blog

Tags :
Writer at Flixtechs Given Ncube's picture
Given Ncube