Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Arrow up icon
GO TO TOP
RxJS Cookbook for Reactive Programming

You're reading from   RxJS Cookbook for Reactive Programming Discover 40+ real-world solutions for building async, event-driven web apps

Arrow left icon
Product type Paperback
Published in Mar 2025
Publisher Packt
ISBN-13 9781788624053
Length 310 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Nikola Mitrovic Nikola Mitrovic
Author Profile Icon Nikola Mitrovic
Nikola Mitrovic
Arrow right icon
View More author details
Toc

Table of Contents (13) Chapters Close

Preface 1. Handling Errors and Side Effects in RxJS 2. Building User Interfaces with RxJS FREE CHAPTER 3. Understanding Reactive Animation Systems with RxJS 4. Testing RxJS Applications 5. Performance Optimizations with RxJS 6. Building Reactive State Management Systems with RxJS 7. Building Progressive Web Apps with RxJS 8. Building Offline-First Applications with RxJS 9. Going Real-Time with RxJS 10. Building Reactive NestJS Microservices with RxJS 11. Index
12. Other Books You May Enjoy

Streaming image loading seamlessly with Progressive Image

In the modern web, we must handle resources that are MBs in size. One such resource is images. Large images can harm performance since they have slower load times, something that could lead to a negative user experience and frustration. To address these issues, one of the common patterns to use is the LowQualityImagePlaceholder pattern, also known as Progressive Image, where we load an image in stages. First, we show the lightweight version of an image (placeholder image). Then, in the background, we load the original image.

How to do it…

In this recipe, we’ll learn how to handle the Progressive Image pattern with ease with the help of RxJS magic.

Step 1 – Defining image sources

Inside our pro-img.component.ts file, we must define paths to our local image and a placeholder/blurry version of the same image from our assets folder:

src = 'image.jpg';
placeholderSrc = 'blurry-image.jpeg';
const img = new Image();
img.src = this.src;
const placeholderImg = new Image();
placeholderImg.src = this.placeholderSrc;

Step 2 – Creating a progress stream

While the image is loading, every 100 milliseconds, we’ll increase the progress percentage, until the load event is triggered. This indicates that the image has been fully loaded. If an error occurs, we’ll say that the progress is at –1:

const loadProgress$ = timer(0, 100);
const loadComplete$ = fromEvent(img, 'load')
    .pipe(map(() => 100));
const loadError$ = fromEvent(img, 'error')
    .pipe(map(() => -1));

Now, we can merge these load events and stream them into the Progressive Image load:

loadingProgress$ = new BehaviorSubject<number>(0);
this.imageSrc$ = merge(loadProgress$, loadComplete$,loadError$).pipe(
    tap((progress) => this.loadingProgress$.next(progress)),
    map((progress) => (progress === 100 ?img.src :placeholderImg.src)),
    startWith(placeholderImg.src),
    takeWhile((src) => src === placeholderImg.src, true),
    catchError(() => of(placeholderImg.src)),
    shareReplay({ bufferSize: 1, refCount: true })
);

We’ll use startWith on the placeholder image and show it immediately in the UI while continuously tracking the progress of the original image load. Once we get 100%, we’ll replace the placeholder image source with the original image.

Step 3 – Subscribing to the image stream in the template

Meanwhile, in the component template, pro-img.component.html, we can subscribe to the progress that’s been made while the image is loading in the background:

<div class="pro-img-container">
    @if ((loadingProgress$ | async) !== 100) {
        <div class="progress">
        {{ loadingProgress$ | async }}%
        </div>
    }
    <img
    [src]="imageSrc$ | async"
    alt="Progressive image"
    class="pro-img"
    >
</div>

Finally, if we open our browser, we may see this behavior in action:

Figure 2.5: Progressive Image
Figure 2.5: Progressive Image

Figure 2.5: Progressive Image

Common gotcha

In this recipe, for simplicity, we’ve chosen to artificially increase the download progress of an image. The obvious drawback is that we don’t get the actual progress of the image download. There’s a way to achieve this effect: by converting the request of an image’s responseType into a blob. More details can be found here: https://stackoverflow.com/questions/14218607/javascript-loading-progress-of-an-image.

See also

You have been reading a chapter from
RxJS Cookbook for Reactive Programming
Published in: Mar 2025
Publisher: Packt
ISBN-13: 9781788624053
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime