Revolutionize Image Loading in Angular: Unleash Peak Performance with NgOptimizedImage Directive
In the fast-paced realm of web development, speed is not just a preference but a demand. Every millisecond counts, and user expectations for quick responsive webpages continue to be high. Consider this scenario: navigating a website with pages that take an eternity to load, leading to frustration and a potential exit.
Now, let's focus on images—the unsung heroes and potential adversaries of user experience and website performance. While they add allure and context, mishandling them hampers speed and degrades user experience, presenting a challenge for developers. Images significantly impact web performance, as highlighted by the 2022 Web Almanac. On mobile, the median image weight is 881 KB, nearly half of a page's total weight, with the average website size at 2019 KB. Images are pervasive, with 99.9% of websites making at least one image request. Notably, on 70% of mobile pages and 80% of desktop pages, the image dictates website render time and perceived loading speed. In technical terms, the Largest Contentful Paint (LCP) often depends on an image, underscoring the critical need for optimizing image loading to enhance web performance and deliver exceptional user experiences.
Overview
NgOptimizedImage in the dynamic landscape of web development stands as a transformative force, where every millisecond counts, and users demand seamless experiences. This blog unravels the intricate balance between speed, user experience, and the impactful world of images. Tailored for web developers, we delve into how NgOptimizedImage, in the realm of Angular development, streamlines image optimization for enhanced web performance. Join us on a journey to decode technical challenges and unveil the immense potential of creating high-performance web applications.
The LCP
What is the LCP, and why is it so important when analyzing website performance?
Largest Contentful Paint (LCP) stands as a pivotal metric within Google's Core Web Vitals initiative, focusing on the loading experience. Ideally, LCP should be kept under 2.5 seconds for both mobile and desktop platforms, and any duration exceeding 4 seconds indicates subpar performance. This metric measures the time elapsed from the initiation of page loading until the largest image or text block renders within the viewport. To ensure a positive user experience, websites aim for an LCP of 2.5 seconds or less in at least 75% of page visits.
When websites bog down due to images, a challenge emerges—balancing allure and potential slowdowns. Angular development tackles this with a suite of image optimization techniques. From WebP images for superior compression to Base64 encoding improving LCP, and lazy loading, these methods, integrated with CDNs, ensure optimal image delivery. However, these approaches often require significant code changes and technical knowledge. Angular's NgOptimizedImage emerges as a streamlined solution, automating image loading prioritization and promoting lazy loading, making optimization more accessible.
At Halodoc, our commitment to efficient web services led us to explore a spectrum of image optimization techniques. Alongside other methodologies, we delved into NgOptimizedImage—an influential Angular component that played a pivotal role in streamlining our development process. The result? Faster, smoother web applications that uphold our dedication to top-notch user experiences. In this blog, we'll explore NgOptimizedImage's exceptional potential for high-performance web applications serving a substantial user base.
What is NgOptimizedImage Directive?
NgOptimizedImage is a powerful directive integrated into the Angular framework, specifically within the Angular common package. It offers developers a streamlined way to implement performance best practices for image loading, making web applications faster, more efficient, and visually captivating. Here's how NgOptimizedImage achieves this feat-
- Prioritizing the LCP Image: NgOptimizedImage takes charge of the loading process, ensuring that the Largest Contentful Paint (LCP) image takes center stage. It does this by automatically setting the
fetchpriority
attribute on<img>
tags. This means that the most crucial content is delivered promptly, resulting in a lightning-fast user experience. - Effortless Lazy Loading: NgOptimizedImage handles lazy loading like a pro. Non-priority images are lazy-loaded by default, ensuring that they don't slow down the loading of essential content. The outcome? A seamless and expedited user journey.
- Streamlined Resource Connections: Web performance is further enhanced as NgOptimizedImage checks for a corresponding pre-connect link tag in the document head. This optimization reduces latency and speeds up page loading.
- Responsive Images: NgOptimizedImage simplifies responsive images by automatically generating the
srcset
attribute. Images adapt gracefully to different screen sizes and resolutions, preserving their visual quality. - SSR Optimization: For applications using Server-Side Rendering (SSR), NgOptimizedImage generates preload hints, ensuring that image loading remains optimized in these scenarios.
Best Practices and Beyond: NgOptimizedImage goes the extra mile by enforcing an array of image best practices. It encourages the use of image Content Delivery Network (CDN) URLs for optimal image loading, insists on explicit width and height attributes to prevent layout shifts, and provides warnings to avoid visual distortions.
Commencing with NgOptimizedImage: A Guide to Integration
Step 1 : Import NgOptimizedImage
The NgOptimizedImage
directive is marked as standalone and can be imported directly.
Step 2: (Optional) Set up a Loader:
An image loader is not required in order to use NgOptimizedImage, but using one with an image CDN enables powerful performance features, including automatic srcset
s for your images.
Step 3: Enable the directive
To activate the NgOptimizedImage
directive, replace your image's src
attribute with ngSrc
.
If you're using a built-in third-party loader, make sure to omit the base URL path from src
, as that will be prepended automatically by the loader.
Step 4: Mark images as priority
Always mark the LCP image on your page as priority
to prioritize its loading.
Marking an image as a priority
applies the following optimizations:
- Sets
fetchpriority=high
(read more about priority hints here) - Sets
loading=eager
(read more about native lazy loading here) - Automatically generates a preload link element if rendered on the server.
Angular displays a warning during development if the LCP element is an image that does not have the priority
attribute. A page’s LCP element can vary based on several factors - such as the dimensions of a user's screen, so a page may have multiple images that should be marked priority
. See CSS for Web Vitals for more details.
Step 5: Include Height and Width
To prevent image-related layout shifts, NgOptimizedImage requires that you specify a height and width for your image, as follows:
For responsive images (images that you've styled to grow and shrink relative to the viewport), the width
and height
attributes should be the intrinsic size of the image file. For responsive images, it's also important to set a value for sizes
.
For fixed-size images, the width
and height
attributes should reflect the desired rendered size of the image. The aspect ratio of these attributes should always match the intrinsic aspect ratio of the image.
Note: If you don't know the size of your images, consider using "fill mode" to inherit the size of the parent container, as described below:
Using fill
mode
When we add the fill
attribute to your image, we do not need and should not include a width
and height
, as in this example:
Important note: For the "fill" image to render properly, its parent element must be styled with position: "relative"
, position: "fixed"
, or position: "absolute"
.
Adjusting image styling
Depending on the image's styling, adding width
and height
attributes may cause the image to render differently. NgOptimizedImage
warns you if your image styling renders the image at a distorted aspect ratio.
You can typically fix this by adding height: auto
or width: auto
to your image styles. For more information, see the web.dev article on the<img>
tag.
If the height
and width
attribute on the image are preventing you from sizing the image the way you want with CSS, consider using "fill" mode instead, and styling the image's parent element.
A Closer Look at their Unique Structure and Configuration
Enhancing Performance: Capturing Pre and Post Metrics with NgOptimizedImage
To understand the true impact of NgOptimizedImage, we embark on a journey to capture pre and post-migration metrics, specifically focusing on the critical Largest Contentful Paint (LCP) and overall performance. This journey will shed light on how NgOptimizedImage can transform the performance landscape of your web applications. So, let's dive into the before and after scenarios, where we'll witness the difference NgOptimizedImage can make.
To assess the effectiveness of the migration, we carefully measured various metrics both Pre-Metrics and Post Metrics of the transition.
Pre Metrics
Post Metrics
Analyzing the Pre and Post Metrics: Observing Performance Enhancements with NgOptimizedImage
Upon a meticulous examination of the pre and post-metrics, a notable improvement in the overall performance of the web application emerges, with a particularly significant impact on the Largest Contentful Paint (LCP). These insights are drawn from the data collected through Lighthouse audits.
It's important to acknowledge that while LCP embodies critical aspects of web performance, it is intrinsically interconnected with other vital parameters. Therefore, the data presented here offers a comprehensive perspective on the influence of NgOptimizedImage. However, it's worth noting that LCP improvements can have ripple effects across various other facets of web performance, resulting in a more seamless and efficient user experience. It's also essential to keep in mind that performance metrics may exhibit variations when examined through alternative tool such as WebPageTest, providing a well-rounded understanding of NgOptimizedImage's impact.
Unlocking Development Advantages with the NgOptimizedImage Directive
The NgOptimizedImage directive not only enhances web performance but also brings significant development benefits to the table.
It enforces some best practices, like:
- Asserting that there is a corresponding pre-connect link tag in the document head
- Using image CDN URLs to apply image optimizations
- Preventing layout shift by requiring width and height
- Warning if width or height has been set incorrectly
- Warning if the image will be visually distorted when rendered
Navigating Hurdles
In this exploration, we navigate these hurdles, uncovering valuable insights and strategies to overcome them effectively.
A few of the hurdles are discussed below:
- Inputs are not dynamic, which means once the values for the inputs are set, they can’t be changed.
So, to handle a use case like below where the image URL is part of some API response:
it needs to be written like this:
2. Mandatory Width and Height Attributes
To ensure smooth functionality, the NgOptimizedImage directive requires the explicit setting of width and height attributes. Failure to do so may result in browser errors.
Conclusion
In closing, our expedition through NgOptimizedImage has illuminated critical insights:
- NgOptimizedImage is a transformative force, reshaping image loading and web performance.
- It prioritizes the Largest Contentful Paint (LCP) image, streamlines resource connections, and enforces image best practices.
- It's not just a feature; it's a commitment to delivering faster and more efficient web applications.
- Integrated into Angular's common package, NgOptimizedImage opens the door to limitless web performance possibilities.
- It empowers developers to address image loading challenges with creativity, redefining the user experience.
NgOptimizedImage transforms web development, especially when combined with other optimization techniques. It's not just a directive, it's a leap forward in crafting high-performance digital experiences. Seamlessly integrating with methods like WebP compression, improved LCP through Base64 encoding, and lazy loading, NgOptimizedImage becomes a powerhouse that redefines web performance. In collaboration with other optimization methodologies, it charts a path to a future where web performance knows no bounds, leaving a lasting impression on every visitor.
References
- NgOptimizedImage Documentation:https://angular.io/api/common/NgOptimizedImage
- Getting started with NgOptimizedImage Documentation: https://angular.io/guide/image-directive#step-5-include-height-and-width
- Other Documentaion:https://angularindepth.com/posts/1511/improve-page-performance-and-lcp-with-ngoptimizedimage
Additional info:-
Here are some of the blogs our team has published, each offering in-depth insights into how we optimized images to enhance user experience and optimize performance. Please feel free to explore these blogs to gain deeper insights:
- Angular Strict Mode: Improving Performance and Reducing Errors
- Tackling some of the key SEO challenges in Angular applications
- Staying Updated with Angular
- Performance Optimization Practices at Halodoc
- Angular Best Practices
- Angular Strict Mode: Improving Performance and Reducing Errors
Join us
Scalability, reliability and maintainability are the three pillars that govern what we build at Halodoc Tech. We are actively looking for engineers at all levels and if solving hard problems with challenging requirements is your forte, please reach out to us with your resumé at careers.india@halodoc.com.
About Halodoc
Halodoc is the number 1 all around Healthcare application in Indonesia. Our mission is to simplify and bring quality healthcare across Indonesia, from Sabang to Merauke. We connect 20,000+ doctors with patients in need through our Tele-consultation service. We partner with 3500+ pharmacies in 100+ cities to bring medicine to your doorstep. We've also partnered with Indonesia's largest lab provider to provide lab home services, and to top it off we have recently launched a premium appointment service that partners with 500+ hospitals that allow patients to book a doctor appointment inside our application. We are extremely fortunate to be trusted by our investors, such as the Bill & Melinda Gates Foundation, Singtel, UOB Ventures, Allianz, GoJek, Astra, Temasek, and many more. We recently closed our Series D round and in total have raised around USD$100+ million for our mission. Our team works tirelessly to make sure that we create the best healthcare solution personalised for all of our patient's needs, and are continuously on a path to simplify healthcare for Indonesia.