From 4ff914a16525350050c5e8359fb59f9d6f243d27 Mon Sep 17 00:00:00 2001 From: Charles Lyding <19598772+clydin@users.noreply.github.com> Date: Mon, 10 Jun 2024 08:46:26 -0400 Subject: [PATCH] fix(@angular/build): allow additional module preloads up to limit If the module preload limit is not met by shallow (depth 1) initial scripts, deeper initial scripts can now be added. This allows for deeper import graphs to take advantage of the browser's module preloading. Additionally, the limit has been increased to ten now that the module preloads are added at the end of the body along with the actual script elements. --- .../src/tools/esbuild/index-html-generator.ts | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/packages/angular/build/src/tools/esbuild/index-html-generator.ts b/packages/angular/build/src/tools/esbuild/index-html-generator.ts index ad238cb8ccb4..afe92dfb0b18 100644 --- a/packages/angular/build/src/tools/esbuild/index-html-generator.ts +++ b/packages/angular/build/src/tools/esbuild/index-html-generator.ts @@ -16,7 +16,7 @@ import { BuildOutputFile, BuildOutputFileType, InitialFileRecord } from './bundl * The maximum number of module preload link elements that should be added for * initial scripts. */ -const MODULE_PRELOAD_MAX = 3; +const MODULE_PRELOAD_MAX = 10; export async function generateIndexHtml( initialFiles: Map, @@ -45,27 +45,25 @@ export async function generateIndexHtml( assert(indexHtmlOptions, 'indexHtmlOptions cannot be undefined.'); if (!externalPackages && indexHtmlOptions.preloadInitial) { - let modulePreloadCount = 0; + const modulePreloads = []; for (const [key, value] of initialFiles) { if (value.entrypoint || value.serverFile) { // Entry points are already referenced in the HTML continue; } - // Only add shallow preloads - if (value.depth > 1) { - continue; - } - - if (value.type === 'script' && modulePreloadCount < MODULE_PRELOAD_MAX) { - modulePreloadCount++; - hints.push({ url: key, mode: 'modulepreload' as const }); + if (value.type === 'script') { + modulePreloads.push({ url: key, mode: 'modulepreload' as const, depth: value.depth }); } else if (value.type === 'style') { // Provide an "as" value of "style" to ensure external URLs which may not have a // file extension are treated as stylesheets. hints.push({ url: key, mode: 'preload' as const, as: 'style' }); } } + + // Limit the number of module preloads with smallest depth given priority + modulePreloads.sort((a, b) => a.depth - b.depth); + hints.push(...modulePreloads.slice(0, MODULE_PRELOAD_MAX)); } /** Virtual output path to support reading in-memory files. */