How to optimize image loading on your website

A website full of images can be a huge bottleneck for website performance. This is how I optimized image loading to accomplish a better user experience.

Joeri Smits
Sep 26, 2017 · 5 min read

Problem

The problem here is that often the site document is already loaded while the images are still loading. This results in empty sections on your page where an image slowly loads in. Not the thing you want.

A simple bad optimized website with a background image of 4.8MB over a fast 3G cellular network

Solution

So how do we overcome this issue? Well, the first thing we can do is to compress the background image by using various tools on the internet. This is an easy win and will reduce the load time to around ten seconds. This seems like a huge step but ten seconds is still way too much.

(() => {
'use strict';
// Page is loaded
const objects = document.getElementsByClassName('asyncImage');
Array.from(objects).map((item) => {
// Start loading image
const img = new Image();
img.src = item.dataset.src;
// Once image is loaded replace the src of the HTML element
img.onload = () => {
item.classList.remove('asyncImage');
return item.nodeName === 'IMG' ?
item.src = item.dataset.src :
item.style.backgroundImage = `url(${item.dataset.src})`;
};
});
})();
<div class="asyncImage" data-src="/images/background.jpg">
...
</div>
<img class="asyncImage" src="/images/background-min.jpg" data-src="/images/background.jpg" alt="Beautiful landscape sunrise">

Conclusion

So what did we do? We improved our user experience, made our website load faster, made it more accessible for users without a fast connection and possibly improved our ranking in Google. That’s a big improvement for such a small change.

The new situation where we first load a low resolution image and then replace it with the original image

Lazy load images

When you want to improve your image loading process even further you might want to consider to lazy load your images.

Frontend Weekly

It's really hard to keep up with all the front-end development news out there. Let us help you. We hand-pick interesting articles related to front-end development. You can also subscribe to our weekly newsletter at http://frontendweekly.co

Thanks to Martijn Schoenmaker.

Joeri Smits

Written by

Lead developer at Webbio • Writes about tech

Frontend Weekly

It's really hard to keep up with all the front-end development news out there. Let us help you. We hand-pick interesting articles related to front-end development. You can also subscribe to our weekly newsletter at http://frontendweekly.co