Liam Docherty
Liam Docherty

Reputation: 39

How can I lazy load an image which is fetched using CSS?

Firstly, the problem I identified on my homepage is that the images make my webpage laggy. I found this article which explained about how to lazy load an image and to me this is a solution to my problem.

However, all the examples relate to the image being fetched using HTML. I fetch my image from my local files using CSS. How can I lazy load my images using CSS for my homepage?

Example of me fetching my image using CSS

background: -webkit-gradient(linear, left top, left bottom, from(rgba(50, 58, 82, 0.8)), to(rgba(50, 58, 82, 0.8))), url(../images/world.jpeg);
background: linear-gradient(to bottom, rgba(50, 58, 82, 0.8), rgba(50, 58, 82, 0.8)), url(../images/world.jpeg);

Here is my GitHub repo if you need to look at any of my website code.

Upvotes: 0

Views: 74

Answers (1)

Aaron Wright
Aaron Wright

Reputation: 178

I think you are asking the wrong question. The images are slowing down your site, so instead of worrying about fancy loading techniques, what you should be asking is how to make the images load faster.

I looked at your page. You have a background image that is almost 7 Mb in size. It is 6,000 px wide. There is no need for an image that big. I downloaded it and used Gimp to scale it down to 3,000 px wide and that slashed the file size to 2 Mb. Running that through an image compressor smashed it down to 800 kb. And even 3,000 px wide might be a little wider than necessary.

You have some other large images that can be slashed too. For example, those logos don't need to be 1000+ px wide if they are only going to be displayed at 230px wide.

Instead of trying to lazy load, you should get back to the more fundamental question of how to quickly load images.

Here are some ideas:

  1. Read about the srcset attribute. It lets the browser choose the best image size based on the different sizes you've made available, as well as other info the browser has available like user preferences and available bandwidth.
  2. Scale your images to multiple different sizes, then use srcset to let the browser load the correct size.
  3. Your background images could probably use CSS media queries to pick the best image size based on screen size. This question has a demo of how to do that.
  4. Use an image compressor to shrink your images. Here is a good one: https://compressor.io/

If you do all of those things and it is still too slow, then you can start getting more creative, but don't make things complicated until you need to.

Upvotes: 1

Related Questions