
Image Optimization for the web is necessary to improve website speed and user experience. There exist numerous techniques and resources for optimizing photos, such as:
Compression: Images can be compressed to save file size without sacrificing quality. You can make use of programs like online image compressors, TinyPNG, and Adobe Photoshop.
Image Formats: Selecting the appropriate image format is important. Photographs work well in JPEG, but transparent images work better in PNG. WebP is a contemporary format with good quality and compression.
Responsive Images: Utilize responsive pictures to present various image sizes according to the screen size and device of the user. In HTML, this can be done by using the srcset attribute.
Lazy Loading: To delay the loading of off-screen images until the user scrolls to them, utilize lazy loading. The HTML loading=”lazy” property can be used for this.
Image CDN: Use a Content Delivery Network (CDN) for photos to ensure effective and efficient image delivery to users.
Image Sprites: To cut down on HTTP requests, group small icons or images together into a single sprite image.
Optimize Alt Text: For SEO and accessibility, make sure all of your image alt text makes sense.
Image Dimensions: To avoid layout shifts while images load, specify the image’s dimensions in HTML.
By using these methods, you may optimize photos on your website and dramatically increase its performance and loading time.
Let’s now examine how to use ngOptimized to optimize the images in Angular.
Adopting performance best practices for loading images which were previously mentioned is made simple by the NgOptimizedImage directive. The NgOptimizedImage directive makes sure that the following factors determine how quickly the Largest Contentful Paint (LCP) picture loads:
- setting the tag’s fetchpriority attribute automatically
- default lazy loading of other pictures
- stating that the document head has a relevant preconnect link tag
- creating a srcset attribute automatically
- Preload hint generation if the application uses SSR
NgOptimizedImage not only optimizes the LCP image loading but also enforces certain image best practices, like:
- Applying image improvements with the help of image CDN URLs
- imposing width and height requirements to stop layout shift
- Alert if width or height are not configured correctly
- Notification if rendering results in a visually distorted picture
Getting started with NgOptimizedImage
1. Import NgOptimizedImage
Import NgOptimizedImage from @angular/common, And add it in the imports array of AppModule.
import { NgOptimizedImage } from '@angular/common';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
NgOptimizedImage
],
providers: [
],
bootstrap: [AppComponent]
})
export class AppModule { }
If you don’t want to add it in NgModule, we can directly import NgOptimizedImage in components as it’s marked as Standalone.
2. Enable the directive
To activate the NgOptimizedImage directive, replace your image’s src attribute with ngSrc.
<img ngSrc="sampleImg.jpg">
3. Mark images as priority
To speed up the loading of the LCP picture on your page, always mark it as priority. Additionally, NgOptimizedImage needs you to give your image the following dimensions: height and width
<img ngSrc="sampleImg.jpg" width="400" height="200" priority>
Marking an image as priority applies the following optimizations:
- Sets fetchpriority=high
- Sets loading=eager
- Preload link element has been generated if rendering on the server.
If you don’t know the size of your images, consider using “fill mode” to inherit the size of the parent container.
<img ngSrc="sampleImg.jpg" fill>
4. Configure a loader.
There are no extra code modifications required to use the default loader. The value of “src” will always match the URL that the generic loader returns. Stated differently, the resource URL is not altered by this loader, and the ngSrc attribute value is utilized exactly as it is.
Add the provider factory for the service you’ve selected to the providers array in order to utilize an already-existing loader for a third-party image service. The Imgix loader is employed in the example that follows:
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 provides the following functions:
You can create a custom loader function If you are using a different image provider than mention above.
To use a custom loader: provide your loader function as a value for the IMAGE_LOADER 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://abc.com/${config.src}-${config.width}.jpg}`;
}
},
],