From d8aa201d0be10dc0d6c006e732dd64f482bf5a77 Mon Sep 17 00:00:00 2001 From: Enea Jahollari Date: Tue, 26 Nov 2024 19:07:13 +0100 Subject: [PATCH] refactor(docs-infra): improve API reference page loading time and drop blocking time (#58911) By scheduling the focus of the input, we can drop the blocking time that is caused by the blocking task of rendering. PR Close #58911 --- .../api-reference-list.component.ts | 29 ++++++++++++++----- 1 file changed, 21 insertions(+), 8 deletions(-) diff --git a/adev/src/app/features/references/api-reference-list/api-reference-list.component.ts b/adev/src/app/features/references/api-reference-list/api-reference-list.component.ts index 7cced57586f..78f6d0a7f04 100644 --- a/adev/src/app/features/references/api-reference-list/api-reference-list.component.ts +++ b/adev/src/app/features/references/api-reference-list/api-reference-list.component.ts @@ -16,7 +16,7 @@ import { model, signal, viewChild, - afterRenderEffect, + afterNextRender, } from '@angular/core'; import ApiItemsSection from '../api-items-section/api-items-section.component'; import {FormsModule} from '@angular/forms'; @@ -56,14 +56,14 @@ export default class ApiReferenceList { filterInput = viewChild.required(TextField, {read: ElementRef}); constructor() { - afterRenderEffect({ - write: () => { - // Lord forgive me for I have sinned - // Use the CVA to focus when https://github.com/angular/angular/issues/31133 is implemented - if (matchMedia('(hover: hover) and (pointer:fine)').matches) { + afterNextRender(() => { + // Lord forgive me for I have sinned + // Use the CVA to focus when https://github.com/angular/angular/issues/31133 is implemented + if (matchMedia('(hover: hover) and (pointer:fine)').matches) { + scheduleOnIdle(() => { this.filterInput().nativeElement.querySelector('input').focus(); - } - }, + }); + } }); effect(() => { @@ -107,3 +107,16 @@ export default class ApiReferenceList { this.type.update((currentType) => (currentType === itemType ? ALL_STATUSES_KEY : itemType)); } } + +/** + * Schedules a function to be run in a new macrotask. + * This is needed because the `requestIdleCallback` API is not available in all browsers. + * @param fn + */ +function scheduleOnIdle(fn: () => void): void { + if (typeof requestIdleCallback !== 'undefined') { + requestIdleCallback(fn); + } else { + setTimeout(fn, 0); + } +}