简体   繁体   中英

Prevent image flicker when setting img src object url in async pipe

I have a JWT authorized endpoint for images, so we can't directly link to image urls in html.

The workaround is to have this async pipe that loads the image with correct authorization (via http interceptor, not shown), and sets the img.src attribute to an "object" url.

HTML:

<img [attr.src]="environment.apiUrl + 'users/image/' + userId | secureImage | async" alt="Avatar" />

Pipe:

import { Pipe, PipeTransform } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Pipe({
    name: 'secureImage'
})
export class SecureImagePipe implements PipeTransform {

    constructor(private http: HttpClient, private sanitizer: DomSanitizer) { }

    transform(url): Observable<SafeUrl> {
        return this.http
            .get(url, { responseType: 'blob' })
            .pipe(map(val => this.sanitizer.bypassSecurityTrustUrl(URL.createObjectURL(val))));
    }
}

As you can see in this GIF, when the image changes from the plus sign (static), to the homer brain (loaded via this pipe), there is a very short flicker where it shows the classic "image not found" along with the alt text (Avatar).

Flicker

How can I prevent this flickering?

UPDATE: Removing the "alt" attributes removes the "broken image" image, which looks much better.

So from this:

<img [attr.src]="environment.apiUrl + 'users/image/' + userId | secureImage | async" alt="Avatar" />

to this:

<img [attr.src]="environment.apiUrl + 'users/image/' + userId | secureImage | async" />

I'm keeping this question open as there may be people that must have the alt attribute, so my solution wouldn't work for them.

When you click the button and load the image, there is a short time frame in which the image is not fully loaded from the server and the < img > will display the alt text.

To prevent this, download the image from the server through a component/service and only set the src once the image is fully done loading.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM