Lazy Loading the Native Way
A while back, I was working on a project in which mobile devices were likely going to be used to consume the results, so my preferred option to displaying images was to lazy load them. In lazy loading, images are only downloaded when they need to be. As an example, if there were an exceptionally large image at the end of your HTML document, but you never scrolled to see it, then it wouldn’t download that resource, saving time and those precious bytes of download quota if on mobile.
Thanks to a recent Syntax podcast, what I didn’t realise, however, was that standards had moved on and there is in fact a native attribute to the img
element that can give you this feature. That means: no JavaScript, no events or depending on the Intersection Observer API. Reducing dependencies has got to be a good thing, right?
Before we begin, be aware that as of this article, caniuse.com states that the 62.71% of browsers support this, with notable exceptions being Safari (unless you specifically enable it) and some Android browsers. Firefox, Chrome, Edge and Opera all do, so you are pretty much covered for most uses.
The loading attribute
So how do we enable this lovely feature? Well, all you need to do is to add the following:
1 | loading="lazy" |
to your img
elements.
Here’s a full example:
1 | <img src="https://cdn.pixabay.com/photo/2020/04/22/01/59/hands-5075436_960_720.jpg" loading="lazy"> |
If you create a simple HTML file and fill it with these, you can see lazy loading in action by opening up the developer tools (F12) and inspecting the network tab as you scroll down the page. As you will realise, they only download when they come into view. Exactly when they appear/download is browser dependent, but hopefully that won’t be an issue for you.
One thing to watch out for is that if you try this with files on your local hard-disk, they won’t be lazy loaded. I think the browser just believes it isn’t necessary, but worth mentioning in case you test this yourself.
Hi! Did you find this useful or interesting? I have an email list coming soon, but in the meantime, if you ready anything you fancy chatting about, I would love to hear from you. You can contact me here or at stephen ‘at’ logicalmoon.com