Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Level Up Your App's Speed with `NgOptimizedImage`
Jarosław Żołnowski
Jarosław Żołnowski

Posted on

Level Up Your App's Speed with `NgOptimizedImage`

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’sNgOptimizedImage 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’sNgOptimizedImage directive makes it easy to get it right without manual tweaks.


Key Features ofNgOptimizedImage

1. Responsive Images withsrcSet andsizes

ThesrcSet andsizes attributes allow the browser to load the right image size for each device, which is especially helpful for performance. The great thing about Angular’sNgOptimizedImage directive is that it generates thesrcSet for you, so you don’t need to do it manually.

Example:

<imgngSrc="angular.jpg"width="200"height="200"sizes="80vw"/>
Enter fullscreen modeExit fullscreen mode

Here,sizes="80vw" sets the image to 80% of the viewport width. Angular will handle the rest, creating asrcSet 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 anIMAGE_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]}}]
Enter fullscreen modeExit fullscreen mode

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 withpriority

Ever noticed how long it can take to load a big image like a banner? Thepriority attribute tells Angular which images are critical for loading first. If you setpriority, Angular preloads the image, making sure it appears quickly, improving that all-important LCP.

Example:

<imgngSrc="hero.jpg"width="1200"height="600"priority/>
Enter fullscreen modeExit fullscreen mode

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:

<imgngSrc="background.jpg"fill/>
Enter fullscreen modeExit fullscreen mode

Just make sure your container hasposition: relative,absolute, orfixed, 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 withloading="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:

<imgngSrc="thumbnail.jpg"width="200"height="200"loading="lazy"/>
Enter fullscreen modeExit fullscreen mode

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. Withplaceholder, 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:

<imgngSrc="profile.jpg"width="200"height="200"placeholder/>
Enter fullscreen modeExit fullscreen mode

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) withNgOptimizedImage, 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 withNgOptimizedImage, 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 theNgOptimizedImage directive can make a big difference in performance. Imagine we’re building a gaming site that displays game cover images.

Preview of the Gaming Site

Here’s the initial setup with the standardsrc attribute:

<imgwidth="1250"height="600"src="https://via.assets.so/game.png?id=12"alt="Assassin's Creed Game Cover Art"/><divstyle="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>
Enter fullscreen modeExit fullscreen mode

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.

Lighthouse Performance Score for Non-Optimized Images

By making a few tweaks withNgOptimizedImage, we can get those numbers way down:

<imgwidth="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/><divstyle="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>
Enter fullscreen modeExit fullscreen mode

To go the extra mile, we add apreconnect link for our image server in the<head>:

<linkrel="preconnect"href="https://via.assets.so/">
Enter fullscreen modeExit fullscreen mode

And in our app configuration, we set up a custom image loader for our CDN (e.g.,Imgix):

constappConfig:ApplicationConfig={providers:[provideImgixLoader('https://via.assets.so/')],};
Enter fullscreen modeExit fullscreen mode

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 howNgOptimizedImage can make a real difference in your app’s speed and user experience.

Lighthouse Performance Score for Optimized Images


Wrapping Up

Angular’sNgOptimizedImage 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. GiveNgOptimizedImage a try and see the difference in your next project!

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

With 17+ years in front-end, I love sharing knowledge through talks, articles, and workshops. I co-host Angular Catch-Up, co-organize Angular Toronto Meetup and strive for clean, high-performance code
  • Location
    Poland, Wroclaw
  • Work
    Lead Technical Architect
  • Joined

More fromJarosław Żołnowski

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp