Images Lazy Loading
IMG tag now supports Lazy loading and more
This section and the image are borrowed from the Addy Osmani's post at LinkedIn.
Tip: <img>
supports lazy-loading, async decoding and much more. Learn about them in my post for Stack Overflow: Picture perfect images with the modern <img> element.
A few more recent posts on <img>
you might appreciate:
- Avoiding <img> layout shifts: aspect-ratio vs width & height attributes by Jake Archibald.
- Optimizing resource loading with Priority Hints (for LCP) by Leena, Patrick Meenan and I (Addy Osmani').
- Optimizing Largest Contentful Paint (recent refresh) by Philip Walton.
Background images Lazy loading
This section is based on the article Lazy Loading Images – The Complete Guide provided by Rahul Nanwani at imagekit.io.
With CSS background images it is not that straightforward. To load CSS background images, the browser needs to build the DOM (Document Object Model) tree, as well as the CSSOM (CSS Object Model) tree, to decide if the CSS style applies to a DOM node in the current document.
If the CSS rule specifying the background image does not apply to an element in the document, then the browser does not load the background image. If the CSS rule is applicable to an element in the current document, then the browser loads the image.
This may seem complex at first, but this same behavior forms the basis of the technique for lazy loading background images. In simple terms, we trick the browser into not applying the background image CSS property to an element till that element comes into the viewport.
An implementation of the approach illustrated by Rahul Nanwani at codepen.io could be found in the script: MediaWiki: Gadget – Template Content Article Header.js.
More references
- MDN: Images in HTML,
- web.dev: Preload key requests,
- web.dev: Preconnect to required origins