From f8b39b087f6eff24850c77c4d10d4268da527c76 Mon Sep 17 00:00:00 2001 From: Andrew Kushnir Date: Tue, 10 May 2022 19:03:44 -0700 Subject: [PATCH] refactor(common): move `NgOptimizedImage` logic that sets `src` to a different hook (#47082) Currently, the logic that sets the `src` on the host `` 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 --- .../src/directives/ng_optimized_image.ts | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/packages/common/src/directives/ng_optimized_image.ts b/packages/common/src/directives/ng_optimized_image.ts index a1a779531b7..fd4dc3dfeba 100644 --- a/packages/common/src/directives/ng_optimized_image.ts +++ b/packages/common/src/directives/ng_optimized_image.ts @@ -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