Using Angular NgOptimizedImage to Implement Image Loading Best Practices

Netanel Basal
Netanel Basal
Published in
2 min readAug 18, 2022

The NgOptimizedImage directive in Angular is responsible for implementing performance best practices when loading images. It’s available in Angular v14.2.0. The directive is marked as standalone and can be imported into standalone components and modules.

To use it, we should replace our image’s src attribute with rawSrc:

The directive will provide us with the following benefits for LCP images:

  • The loading attribute of images below the fold will be set to lazy, while the loading attribute of images above the fold (LCP one) will be eager.
  • It’ll ensure we use the priority input for above-the-fold images. This will set the fetchpriority attribute to high. The default is auto.
  • It’ll ensure that images above the fold have a corresponding preconnect link tag.
  • It’ll ensure that width and height are set to prevent image-related layout shifts
  • It’ll ensure that images will be visually distorted when rendered

The word “ensure” means it will warn you if that isn’t the case.

Image Loaders

A loader is a function that generates the appropriate resource URL for a given image file. The default loader returns the src we pass to the rawSrc input. Angular provides various loaders for third-party image services:

  • Cloudflare Image Resizing
  • Cloudinary
  • ImageKit
  • Imgix

To use it, we must pass the provider factory for the chosen service to the providers array:

We can create a custom loader by overriding the IMAGE_LOADER provider:

The preview docs provide more information about the API:

Follow me on Medium or Twitter to read more about Angular and JS!

--

--

Netanel Basal
Netanel Basal

Written by Netanel Basal

A FrontEnd Tech Lead, blogger, and open source maintainer. The founder of ngneat, husband and father.

Responses (4)