Copy
You are reading the Ruby on Rails performance newsletter by Speedshop.

Lazy-loading images used to be hard, but with loading="lazy", it's now super-simple.

Firefox 75 and Chrome 76 have a fancy new feature - an attribute you can add to elements called loading. Technically, it's a valid attribute on any HTML element, but for now it only works on images and iframes.

When you add
loading="lazy" to an element, you change how the browser decides to fetch that image.

Normally, all image and iframe elements on a page are fetched before the load event can be fired. Basically, most browsers start downloading all the images on a page as the important stuff, like CSS and JS, is downloaded.

But with
loading="lazy", instead that element no longer blocks the load event and will be downloaded only when it enters the viewport.

This matters for a few reasons:
  • This is a big bandwidth saver. Offscreen images account for about 300kB of bandwidth on mobile sites, according to HTTPArchive. That's bandwidth that your users have to pay for and never actually use.
  • It means on-screen images load faster. Browsers may not prioritize on-screen images. This means that loading 1 on-screen image will proceed slower if we also need to download 4 off-screen images in the background.
  • This saves our own bandwidth costs. If you're paying per-GB, this could definitely add up, because images are often 50% or more of total page size.
loading=lazy currently sits at 63% adoption. In my opinion, you should start adding this to your applications now to benefit the majority of your users.

Currently, the big adoption "blindspot" is basically Safari, mobile and desktop, which accounts for 15-20% of global usage. There are polyfills available if you feel the need to serve these markets additionally.

You may need to consider adding heights to your image elements in order to prevent a flash-of-unstyled content or excessive document reflowing.

So, should you do this for all images, all the time? I think you certainly could - it's what I'm doing on my sites now. The only thing you might have to watch out for is the unblocking of the load event: images are no longer loaded when that event fires, so you may have some document reflowing going on after the load event as those things get loaded in.

I think this attribute works particuarly well for long pages, infinite scrolls, or blog posts. I added it to most images on speedshop.co.

So - here's your free perf PR of the week. Go save your users some bandwidth!

-Nate
You can share this email with this permalink: https://mailchi.mp/railsspeed/lazy-load-your-images-today-and-get-a-quick-perf-boost-w1-quick-change?e=[UNIQID]

Copyright © 2020 Nate Berkopec, All rights reserved.


Want to change how you receive these emails?
You can update your preferences or unsubscribe from this list.

Email Marketing Powered by Mailchimp