If you've worked on a web app, you know that images can be a big deal for both design and performance. While they make pages look great, they can also slow everything down. That’s where Angular’s NgOptimizedImage
directive comes in. It’s a handy tool for optimizing images, so they load faster without losing quality. Let’s dive into how this directive can make your Angular app snappier and improve the user experience.
Why Optimize Images Anyway?
We all want our apps to look good, but images come with a cost—longer load times. Optimizing images can dramatically improve performance metrics, especially the Largest Contentful Paint (LCP), which measures how fast the largest piece of content appears on the screen. This is huge for user experience and SEO, and Angular’s NgOptimizedImage
directive makes it easy to get it right without manual tweaks.
Key Features of NgOptimizedImage
1. Responsive Images with srcSet
and sizes
The srcSet
and sizes
attributes allow the browser to load the right image size for each device, which is especially helpful for performance. The great thing about Angular’s NgOptimizedImage
directive is that it generates the srcSet
for you, so you don’t need to do it manually.
Example:
<img
ngSrc="angular.jpg"
width="200"
height="200"
sizes="80vw"
/>
Here, sizes="80vw"
sets the image to 80% of the viewport width. Angular will handle the rest, creating a srcSet
with various resolutions so that each device gets the best fit. This saves time and ensures a smooth load no matter the screen size.
2. Customizing Image Breakpoints
If you’re working with specific screen sizes, Angular lets you customize breakpoints by setting an IMAGE_CONFIG
token. This way, you can pick just the breakpoints that match your app’s design.
Example:
providers: [{
provide: IMAGE_CONFIG,
useValue: {
breakpoints: [384, 640, 750]
}
}]
Now Angular will only generate images for 384px, 640px, and 750px, which keeps your file sizes smaller and your app faster.
3. Prioritizing Key Images with priority
Ever noticed how long it can take to load a big image like a banner? The priority
attribute tells Angular which images are critical for loading first. If you set priority
, Angular preloads the image, making sure it appears quickly, improving that all-important LCP.
Example:
<img
ngSrc="hero.jpg"
width="1200"
height="600"
priority
/>
For server-side rendered apps, Angular even adds a <link rel="preload">
tag for these images, so they start loading right away. This is perfect for hero images or banners that you want users to see immediately.
4. Fill Mode for Flexible Layouts
Need an image to fill a container, like a background? fill
mode has you covered. It lets an image scale to fit the container without needing fixed dimensions, which is perfect for layouts with unknown widths or heights.
Example:
<img ngSrc="background.jpg" fill />
Just make sure your container has position: relative
, absolute
, or fixed
, so the image fills it properly. This feature is great for responsive layouts where you want images to adapt smoothly.
5. Lazy Loading for Off-Screen Images
Angular makes lazy loading effortless with loading="lazy"
, which defers loading images until they’re about to be visible. This reduces the initial page load and is awesome for things like image galleries.
Example:
<img
ngSrc="thumbnail.jpg"
width="200"
height="200"
loading="lazy"
/>
Just be cautious with images that are crucial to the layout, like a logo. For these, skip lazy loading to ensure they load right away.
6. Placeholders for a Better Loading Experience
Nothing kills user experience like a blank loading image. With placeholder
, you can show a temporary low-res version or even a Base64-encoded preview while the main image loads. This provides a smoother experience as users see a preview of the image right away.
Example:
<img
ngSrc="profile.jpg"
width="200"
height="200"
placeholder
/>
If you use a CDN, you can generate low-res placeholders automatically. Just keep them small (under 4 KB) to avoid slowing down the load. Angular will even throw an error if the placeholder size is too big, which is a good reminder to keep things light.
CDN Integration for Faster Image Delivery
By using a Content Delivery Network (CDN) with NgOptimizedImage
, you get faster load times because images are served from servers closer to your users. CDNs cache content across the globe, meaning shorter load times and less data travel, which makes a huge difference, especially for users far from your primary server.
CDNs also often compress images, ensuring the best quality at the smallest size, which boosts performance even further. When combined with NgOptimizedImage
, CDNs can help you build a fast, responsive app that works well for users everywhere.
A Practical Example
Now, let's look at a real-world example to see how the NgOptimizedImage
directive can make a big difference in performance. Imagine we’re building a gaming site that displays game cover images.
Here’s the initial setup with the standard src
attribute:
<img
width="1250"
height="600"
src="https://via.assets.so/game.png?id=12"
alt="Assassin's Creed Game Cover Art"
/>
<div style="display: flex; gap: 25px; margin-top: 25px;">
<img
*ngFor="let image of list; trackBy: $index"
src="https://via.assets.so/game.png?id=16"
width="400"
height="200"
alt="Thumbnails Movie Gallery"
/>
</div>
When we analyze the page in Lighthouse, the First Contentful Paint (FCP) comes in at 1.4 seconds, while the Largest Contentful Paint (LCP) lags behind at 13.5 seconds—not ideal.
By making a few tweaks with NgOptimizedImage
, we can get those numbers way down:
<img
width="1250"
height="600"
src="game.png?id=12"
ngSrcset="400w, 800w, 1200w"
sizes="(max-width: 600px) 960px, 100vw"
alt="Witcher II Game Cover Art"
priority
/>
<div style="display: flex; gap: 25px; margin-top: 25px;">
<img
*ngFor="let image of list; trackBy: $index"
width="400"
height="200"
[ngSrc]="game.png?id=16"
ngSrcset="100w, 200w, 400w"
sizes="(max-width: 600px) 200px, 400px"
alt="Thumbnails Movie Gallery"
priority
/>
</div>
To go the extra mile, we add a preconnect
link for our image server in the <head>
:
<link rel="preconnect" href="https://via.assets.so/">
And in our app configuration, we set up a custom image loader for our CDN (e.g., Imgix
):
const appConfig: ApplicationConfig = {
providers: [provideImgixLoader('https://via.assets.so/')],
};
With these small adjustments, we see a huge performance boost—FCP drops to just 0.2 seconds, and LCP is down to a quick 0.7 seconds! This is a perfect example of how NgOptimizedImage
can make a real difference in your app’s speed and user experience.
Wrapping Up
Angular’s NgOptimizedImage
is a fantastic tool for improving image handling and app performance. Whether you’re working with responsive images, lazy loading, or CDN integration, this directive makes it easy to get things right. With these optimizations, you’ll have a faster, smoother app that keeps users happy. Give NgOptimizedImage
a try and see the difference in your next project!
Top comments (0)