Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Preload the app bundles from the top of <head> (#80134)

Romeo Van Snicka444fcd2af80
diff --git a/resources/frontend_client/index_template.html b/resources/frontend_client/index_template.html
index 2c2c78696af..e967250fddd 100644
--- a/resources/frontend_client/index_template.html
+++ b/resources/frontend_client/index_template.html
@@ -23,6 +23,12 @@
<base href="{{{baseHref}}}" />
+ <!--
+ PreloadAssetTags replaces this marker at build time. Keep it after <base href>,
+ which the hints resolve against, and before the inline JSON, which is large.
+ -->
+ <!-- asset-preloads -->
+
<script type="application/json" id="_metabaseBootstrap">
{{{bootstrapJSON}}}
</script>
diff --git a/rspack.main.config.js b/rspack.main.config.js
index a08a99a4abd..5b0480e2217 100644
--- a/rspack.main.config.js
+++ b/rspack.main.config.js
@@ -118,6 +118,55 @@ class OnScriptError {
}
}
+const PRELOAD_MARKER = "<!-- asset-preloads -->";
+
+/**
+ * The bundle tags are injected at the end of <head>, after ~124 kB of inline JSON,
+ * so the browser only discovers them once nearly the whole document has arrived.
+ * This emits `rel=preload` copies near the top of <head> instead, where they land in
+ * the first flight of response bytes. Templates without the marker are left alone.
+ */
+class PreloadAssetTags {
+ apply(/** @type {import("webpack").Compiler} */ compiler) {
+ compiler.hooks.compilation.tap(
+ "PreloadAssetTags",
+ (/** @type {import("webpack").Compilation} */ compilation) => {
+ HtmlWebpackPlugin.getHooks(compilation).afterTemplateExecution.tapAsync(
+ "PreloadAssetTags",
+ (data, cb) => {
+ if (!data.html.includes(PRELOAD_MARKER)) {
+ cb(null, data);
+ return;
+ }
+
+ const hints = data.headTags
+ .flatMap((tag) => {
+ if (tag.tagName === "script" && tag.attributes.src) {
+ return [{ url: tag.attributes.src, as: "script" }];
+ }
+ if (
+ tag.attributes.rel === "stylesheet" &&
+ tag.attributes.href
+ ) {
+ return [{ url: tag.attributes.href, as: "style" }];
+ }
+ return [];
+ })
+ .map(
+ (hint) =>
+ `<link rel="preload" href="${hint.url}" as="${hint.as}">`,
+ )
+ .join("");
+
+ data.html = data.html.replace(PRELOAD_MARKER, hints);
+ cb(null, data);
+ },
+ );
+ },
+ );
+ }
+}
+
/** @type {import('@rspack/cli').Configuration} */
const config = {
mode: isDevMode ? "development" : "production",
@@ -312,6 +361,7 @@ const config = {
ignoreOrder: true,
}),
new OnScriptError(),
+ new PreloadAssetTags(),
new HtmlWebpackPlugin({
filename: "../../index.html",
chunksSortMode: "manual",