Boost Image Loading Performance with NgOptimizedImage Directive

Navneet Singh
4 min readJul 11, 2023

--

Images are an integral part of modern web design, but they can also be a significant factor in slowing down page load times. To address this issue, Angular provides the NgOptimizedImage directive, a powerful tool that enforces best practices and improves image loading performance. In this article, we will explore the features and usage of the NgOptimizedImage directive to optimize image loading in Angular applications.

Understanding the NgOptimizedImage Directive

The NgOptimizedImage directive is designed to prioritize the loading of the Largest Contentful Paint (LCP) image, enhancing overall performance. Let’s take a closer look at its properties and functionality:

Selectors

The directive is applied to img elements using the following selector:

img[ngSrc]

Properties

The NgOptimizedImage directive provides several properties to customize the image loading behavior. Let’s explore each property in detail:

  • ngSrc: This property specifies the name of the source image. The image loader processes the image name, and the final URL is applied as the src property of the img element.
  • ngSrcset: This property accepts a comma-separated list of width or density descriptors. The image name from ngSrc is combined with the list of descriptors to generate the srcset property of the img element. This property enables responsive images.
  • sizes: The sizes property is used to pass the base sizes attribute to the img element, enabling automatic responsive srcset creation.
  • width and height: These properties define the intrinsic dimensions of the image. For responsive images, they represent the intrinsic width and height in pixels. For fixed-size images, they indicate the desired rendered width and height in pixels.
  • loading: This property controls the loading behavior of the image. It can be set to 'lazy', 'eager', or 'auto'. Setting images as loading='eager' or loading='auto' marks them as non-priority images, while 'lazy' loading defers loading until the image is about to be displayed. It is recommended to avoid changing this input for priority images.
  • priority: Setting the priority property to true indicates that the image should have a high priority during loading.
  • loaderParams: This property allows passing custom data to custom loaders.
  • disableOptimizedSrcset: Enabling this property disables automatic srcset generation for the image.
  • fill: This property, marked as DEVELOPER PREVIEW, enables “fill mode” for the image. In this mode, the image fills its containing element without requiring explicit height and width values.

Functionality

The NgOptimizedImage directive offers several features to enhance image loading performance:

  • Automatically sets the fetchpriority attribute on the img tag to prioritize loading of the Largest Contentful Paint (LCP) image.
  • Lazy loads non-priority images by default.
  • Asserts the presence of a corresponding preconnect link tag in the document head.
  • Generates appropriate asset URLs if a corresponding ImageLoader function is provided.
  • Automatically generates a srcset based on the provided descriptors.
  • Requires the width and height properties to be set and warns if they are incorrect or may cause visual distortion when rendered.

Implementing the NgOptimizedImage Directive

To leverage the benefits of the NgOptimizedImage directive in your Angular application, follow these steps:

Step 1: Import the NgOptimizedImage directive

Start by importing the NgOptimizedImage directive into the necessary NgModule or a standalone component:

import { NgOptimizedImage } from '@angular/common';

// Include it in the necessary NgModule
@NgModule({
imports: [NgOptimizedImage],
})
class AppModule {}

// ... or a standalone Component
@Component({
standalone: true,
imports: [NgOptimizedImage],
})
class MyStandaloneComponent {}

Step 2: Configure a loader

To use the default loader, no additional code changes are necessary. The URL returned by the generic loader will always match the value of src. In other words, the default loader applies no transformations to the resource URL, and the value of the ngSrc attribute is used as is.

If you want to use an existing loader for a third-party image service, add the provider factory for your chosen service to the providers array. For example, to use the Imgix loader:

import { provideImgixLoader } from '@angular/common';

// Call the function and add the result to the `providers` array:
providers: [
provideImgixLoader("https://my.base.url/"),
],

The NgOptimizedImage directive also provides functions for specific image providers, such as provideCloudflareLoader, provideCloudinaryLoader, provideImageKitLoader, and provideImgixLoader. If you use a different image provider, you can create a custom loader function.

To use a custom loader, provide your loader function as a value for the IMAGE_LOADER dependency injection (DI) token:

import { IMAGE_LOADER, ImageLoaderConfig } from '@angular/common';

// Configure the loader using the `IMAGE_LOADER` token.
providers: [
{
provide: IMAGE_LOADER,
useValue: (config: ImageLoaderConfig) => {
return `https://example.com/${config.src}-${config.width}.jpg}`;
},
},
],

Step 3: Update img tags in templates

Finally, update the <img> tags in your templates to use the ngSrc property instead of the src attribute:

<img ngSrc="logo.png" width="200" height="100">

By using ngSrc, the directive gains control over when the src attribute is set, triggering image downloads at the optimal time.

Conclusion

The NgOptimizedImage directive is a valuable tool for improving image loading performance in Angular applications. By following the steps outlined in this article, you can easily implement the directive and enforce best practices for image loading. Leveraging features like automatic srcset generation, lazy loading, and priority handling, NgOptimizedImage empowers you to optimize your web application's user experience by ensuring that images load efficiently.

Remember to consider the specific requirements of your application and choose the appropriate image loader or create a custom loader to integrate with your preferred image hosting service. With NgOptimizedImage, you can strike the right balance between performance and visual quality, delivering an exceptional image loading experience to your users.

--

--