Skip to content

Commit fafcb0d

Browse files
arturovtAndrewKushnir
authored andcommitted
fix(common): scan images once page is loaded (#52991)
This commit updates the implementation of the `ImagePerformanceWarning` and runs the image scan even if the page has already been loaded. The `window.load` event would never fire if the page has already been loaded; that's why we're checking for the document's ready state. PR Close #52991
1 parent 492ad46 commit fafcb0d

File tree

1 file changed

+12
-3
lines changed

1 file changed

+12
-3
lines changed

packages/core/src/image_performance_warning.ts

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@ const SCAN_DELAY = 200;
2222

2323
const OVERSIZED_IMAGE_TOLERANCE = 1200;
2424

25-
2625
@Injectable({providedIn: 'root'})
2726
export class ImagePerformanceWarning implements OnDestroy {
2827
// Map of full image URLs -> original `ngSrc` values.
@@ -38,7 +37,8 @@ export class ImagePerformanceWarning implements OnDestroy {
3837
return;
3938
}
4039
this.observer = this.initPerformanceObserver();
41-
const win = getDocument().defaultView;
40+
const doc = getDocument();
41+
const win = doc.defaultView;
4242
if (typeof win !== 'undefined') {
4343
this.window = win;
4444
// Wait to avoid race conditions where LCP image triggers
@@ -49,7 +49,16 @@ export class ImagePerformanceWarning implements OnDestroy {
4949
// Angular doesn't have to run change detection whenever any asynchronous tasks are invoked in
5050
// the scope of this functionality.
5151
this.ngZone.runOutsideAngular(() => {
52-
this.window?.addEventListener('load', waitToScan, {once: true});
52+
// Consider the case when the application is created and destroyed multiple times.
53+
// Typically, applications are created instantly once the page is loaded, and the
54+
// `window.load` listener is always triggered. However, the `window.load` event will never
55+
// be fired if the page is loaded, and the application is created later. Checking for
56+
// `readyState` is the easiest way to determine whether the page has been loaded or not.
57+
if (doc.readyState === 'complete') {
58+
waitToScan();
59+
} else {
60+
this.window?.addEventListener('load', waitToScan, {once: true});
61+
}
5362
});
5463
}
5564
}

0 commit comments

Comments
 (0)