Lazy Load Images in Angular with just a few lines of code!
- Tram Ho
Image lazy loading reduces the load of the current image when it is not yet needed to be displayed in the viewport. The like image will only be loaded when the user scrolls to the image to display. Using this technique, we can achieve better performance and load times.
Nowadays, modern browsers have added support for lazy loading images and we can use it by simply adding an attribute to the element. image
:
<img src="src.png" alt="Angular" loading="lazy">
Properties loading
support three options – auto, eager, and lazy. With the lazy option will delay resource loading until a calculated distance from the viewport is reached.
Let’s create a directive to seamlessly add this attribute if the browser supports it:
1 2 3 4 5 6 7 8 9 10 11 12 13 | import { Directive, ElementRef } from '@angular/core'; @Directive({ selector: 'img' }) export class LazyImgDirective { constructor({ nativeElement }: ElementRef<HTMLImageElement>) { const supports = 'loading' in HTMLImageElement.prototype; if (supports) { nativeElement.setAttribute('loading', 'lazy'); } } } |
First we check if the browser supports this feature or not. If so, we add the loading attribute; If not, we leave it as default.
One more step we can take when the browser doesn’t support it is to call the callback IntersectionObserver
( does not support IE)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import { Directive, ElementRef } from '@angular/core'; @Directive({ selector: 'img' }) export class LazyImgDirective { constructor({ nativeElement }: ElementRef<HTMLImageElement>) { const supports = 'loading' in HTMLImageElement.prototype; if (supports) { nativeElement.setAttribute('loading', 'lazy'); } else { // fallback to IntersectionObserver } } } |
In case you missed it Here are some of my open source projects: Akita: State management designed specifically for JS applications Spectator: A powerful tool to simplify tests your perspective Transloco: Angular Internationalization Library Form Manager: A Platform for Proper Form Management in Angular Cashew: A Flexible and Simple Library That Hosts HTTP Requests Error Tailor – Expression Error Seamless pattern for Angular apps And many more!
Reference: Some open source projects:
- Akita: State Management Tailored-Made for JS Applications
- Spectator: A Powerful Tool to Simplify Your Angular Tests
- Transloco: The Internationalization library Angular
- Forms Manager: The Foundation for Proper Form Management in Angular
- Cashew: A flexible and straightforward library that caches HTTP requests
- Error Tailor — Seamless form errors for Angular applications
Follow me on Medium or Twitter to read more about Angular, Akita and JS!
the source: https://netbasal.com/lazy-load-images-in-angular-with-two-lines-of-code-beb13cd5a1c4