Google PageSpeed insights have given us a new opportunity that we want to tackle. Defer offscreen images or lazy loading. Before we begin, we get a little technical in this article. If you just want the solution then skip straight to our Defer offscreen images recipe.
Lazy loading explained
Lazy loading (also called asynchronous loading) has an older, more successful sibling called eager loading. Eager loading takes everything you need to view a website, downloads and processes as soon as we visit the website. Eager loading used to be the popular sibling until we realised we don’t need everything straight away. Lazy loading does this slowly only when you need something. Working smarter, not harder, is a lazy loading motto. You don’t need an image at the bottom of the page if you never get that far.
Lazy loading is a way of deferring items that are not needed for right now, instead of downloading everything just in case.
Lazy loading tips
When implementing lazy loading, consider:
- Only lazy load resources outside of a user’s view and not required in our initial load. EG: this page opens on our logo, menu and feature image. We don’t need the recipe roundup boxes at the bottom of this page straight away.
- We should insert lazy loaded images into view via JavaScript to avoid crashing our browser.
- Use a noscript alternative in case someone disabled JavaScript in the user’s browser.
What is it good for?
Lazy loading can help defer loading of images, fonts, CSS, script and anything else you can think of. If our browser has to download it, we can defer. It’s up to us to decide what we defer and what users need in the initial load.
Defer offscreen images and implement lazy loading
To implement lazy loading via HTML, we just can use the loading tag on any image
<img src="image.jpg" alt="..." loading="lazy">
Struggling with the above recipe? Hire a chef to do it for you