mirror of
https://github.com/angular/angular.git
synced 2026-09-14 13:54:52 +08:00
refactor(common): move NgOptimizedImage logic that sets src to a different hook (#47082)
Currently, the logic that sets the `src` on the host `<img>` element is located in the `ngOnChanges` lifecycle hook and guarded by the dev-mode checks that the inputs do not change. However, those checks would be tree-shaken in prod mode and the `src` would be set each time the `ngOnChanges` hook is invoked. This is undesirable and may potentially lead to performance issues. This commit moves the `src`-related logic to the `ngOnInit` hook instead, which would have the same effect (executed only once, after all inputs are set) and would behave consistently in dev and prod modes. PR Close #47082
This commit is contained in:
committed by
Pawel Kozlowski
parent
4a01b204d3
commit
f8b39b087f
@@ -132,12 +132,6 @@ export class NgOptimizedImage implements OnInit, OnChanges {
|
||||
assertRequiredNumberInput(this, this.width, 'width');
|
||||
assertRequiredNumberInput(this, this.height, 'height');
|
||||
}
|
||||
}
|
||||
|
||||
ngOnChanges(changes: SimpleChanges) {
|
||||
if (ngDevMode) {
|
||||
assertNoPostInitInputChange(this, changes, ['rawSrc', 'width', 'height', 'priority']);
|
||||
}
|
||||
this.setHostAttribute('loading', this.getLoadingBehavior());
|
||||
this.setHostAttribute('fetchpriority', this.getFetchPriority());
|
||||
// The `src` attribute should be set last since other attributes
|
||||
@@ -145,15 +139,21 @@ export class NgOptimizedImage implements OnInit, OnChanges {
|
||||
this.setHostAttribute('src', this.getRewrittenSrc());
|
||||
}
|
||||
|
||||
getLoadingBehavior(): string {
|
||||
ngOnChanges(changes: SimpleChanges) {
|
||||
if (ngDevMode) {
|
||||
assertNoPostInitInputChange(this, changes, ['rawSrc', 'width', 'height', 'priority']);
|
||||
}
|
||||
}
|
||||
|
||||
private getLoadingBehavior(): string {
|
||||
return this.priority ? 'eager' : 'lazy';
|
||||
}
|
||||
|
||||
getFetchPriority(): string {
|
||||
private getFetchPriority(): string {
|
||||
return this.priority ? 'high' : 'auto';
|
||||
}
|
||||
|
||||
getRewrittenSrc(): string {
|
||||
private getRewrittenSrc(): string {
|
||||
const imgConfig = {
|
||||
src: this.rawSrc,
|
||||
// TODO: if we're going to support responsive serving, we don't want to request the width
|
||||
|
||||
Reference in New Issue
Block a user