Skip to content

Build your personal knowledge base with Trilium Notes

perf(client): preload the text editor's modules while idle

Elian Doran9878b281ec24
diff --git a/apps/client/src/desktop.ts b/apps/client/src/desktop.ts
index fddd23ee90..7d81dfd0e2 100644
--- a/apps/client/src/desktop.ts
+++ b/apps/client/src/desktop.ts
@@ -14,6 +14,7 @@ import noteTooltipService from "./services/note_tooltip.js";
import { setBackgroundEffectsSuspended } from "./services/theme.js";
import toastService from "./services/toast.js";
import utils from "./services/utils.js";
+import { preloadCommonNoteTypes } from "./widgets/note_types.js";
await appContext.earlyInit();
@@ -22,7 +23,10 @@ bundleService.getWidgetBundlesByParent().then(async (widgetBundles) => {
const DesktopLayout = (await import("./layouts/desktop_layout.js")).default;
appContext.setLayout(new DesktopLayout(widgetBundles));
- appContext.start().then(reportFullRenderStartupMetric).catch((e) => {
+ appContext.start().then(() => {
+ reportFullRenderStartupMetric();
+ preloadCommonNoteTypes();
+ }).catch((e) => {
toastService.showPersistent({
id: "critical-error",
title: t("toast.critical-error.title"),
diff --git a/apps/client/src/mobile.ts b/apps/client/src/mobile.ts
index de219db93d..5bf5b4ea7e 100644
--- a/apps/client/src/mobile.ts
+++ b/apps/client/src/mobile.ts
@@ -4,6 +4,7 @@ import appContext from "./components/app_context.js";
import { setupClipboardImageEmbed } from "./services/clipboard_image_embed.js";
import glob from "./services/glob.js";
import noteAutocompleteService from "./services/note_autocomplete.js";
+import { preloadCommonNoteTypes } from "./widgets/note_types.js";
glob.setupGlobs();
@@ -17,4 +18,4 @@ setupClipboardImageEmbed();
const MobileLayout = (await import("./layouts/mobile_layout.js")).default;
appContext.setLayout(new MobileLayout());
-appContext.start();
+void appContext.start().then(preloadCommonNoteTypes);
diff --git a/apps/client/src/widgets/note_types.spec.ts b/apps/client/src/widgets/note_types.spec.ts
new file mode 100644
index 0000000000..15dd946590
--- /dev/null
+++ b/apps/client/src/widgets/note_types.spec.ts
@@ -0,0 +1,76 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+/**
+ * Loads a fresh copy of the module, so that the "only the first call counts" latch of
+ * `preloadCommonNoteTypes` starts out untripped in every test.
+ */
+async function loadModule() {
+ vi.resetModules();
+ return import("./note_types");
+}
+
+describe("preloadCommonNoteTypes", () => {
+ let idleCallbacks: (() => void)[];
+
+ beforeEach(() => {
+ idleCallbacks = [];
+ vi.stubGlobal("requestIdleCallback", (callback: () => void) => {
+ idleCallbacks.push(callback);
+ return 1;
+ });
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it("fetches the text editor's module once the browser is idle, and only ever once", async () => {
+ const { preloadCommonNoteTypes, TYPE_MAPPINGS } = await loadModule();
+ const view = vi.fn(() => Promise.resolve({ default: () => undefined }));
+ TYPE_MAPPINGS.editableText.view = view;
+
+ // Merely asking for the preload must not fetch anything yet — the whole point is to wait for
+ // a moment where the application has nothing better to do.
+ preloadCommonNoteTypes();
+ expect(view).not.toHaveBeenCalled();
+ expect(idleCallbacks).toHaveLength(1);
+
+ idleCallbacks[0]();
+ expect(view).toHaveBeenCalledOnce();
+
+ // Repeated calls (e.g. a second window, or a restart of the layout) are a no-op: the module
+ // is in hand already, and re-importing it would only add noise.
+ preloadCommonNoteTypes();
+ expect(idleCallbacks).toHaveLength(1);
+ expect(view).toHaveBeenCalledOnce();
+ });
+
+ it("swallows a failed fetch rather than leaving an unhandled rejection behind", async () => {
+ const { preloadCommonNoteTypes, TYPE_MAPPINGS } = await loadModule();
+ const rejection = Promise.reject(new Error("offline"));
+ TYPE_MAPPINGS.editableText.view = () => rejection;
+
+ preloadCommonNoteTypes();
+ idleCallbacks[0]();
+
+ await expect(rejection.catch(() => "handled")).resolves.toBe("handled");
+ });
+
+ it("falls back to a timer where the browser has no notion of idleness", async () => {
+ vi.stubGlobal("requestIdleCallback", undefined);
+ vi.useFakeTimers();
+ try {
+ const { preloadCommonNoteTypes, TYPE_MAPPINGS } = await loadModule();
+ const view = vi.fn(() => Promise.resolve({ default: () => undefined }));
+ TYPE_MAPPINGS.editableText.view = view;
+
+ preloadCommonNoteTypes();
+ expect(view).not.toHaveBeenCalled();
+
+ vi.runAllTimers();
+ expect(view).toHaveBeenCalledOnce();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
diff --git a/apps/client/src/widgets/note_types.tsx b/apps/client/src/widgets/note_types.tsx
index e9baab6f9e..214d34d409 100644
--- a/apps/client/src/widgets/note_types.tsx
+++ b/apps/client/src/widgets/note_types.tsx
@@ -171,3 +171,51 @@ export const TYPE_MAPPINGS: Record<ExtendedNoteType, NoteTypeMapping> = {
isFullHeight: true
}
};
+
+/** The note types whose modules are fetched ahead of time by {@link preloadCommonNoteTypes}. */
+const PRELOADED_NOTE_TYPES: ExtendedNoteType[] = [ "editableText" ];
+
+let preloadRequested = false;
+
+/**
+ * Fetches ahead of time the modules of the note types most likely to be displayed, so that the first
+ * note to be displayed does not have to wait for them.
+ *
+ * The text note's are by far the largest: its editor — CKEditor together with Trilium's plugins for
+ * it — is around 1.4 MB of script (≈ 375 kB compressed), fetched and parsed only once a text note is
+ * actually shown. That is long enough to be felt as a delay when opening the first text note after a
+ * reload, or when clicking a calendar event to have it open in the popup editor. Fetching it while
+ * the application sits idle instead moves that cost away from the moment the user is waiting on it.
+ *
+ * Deliberately kept to the text note: note types are lazily loaded so that a session never pays for
+ * what it never displays, and warming more of them would erode that. Creating the editor itself is
+ * comparatively cheap (tens of milliseconds), so only the modules are fetched here — no editor is
+ * built in advance.
+ *
+ * Calling this more than once does nothing: the first call is the one that counts.
+ */
+export function preloadCommonNoteTypes() {
+ if (preloadRequested) return;
+ preloadRequested = true;
+
+ whenIdle(() => {
+ for (const noteType of PRELOADED_NOTE_TYPES) {
+ // A failure here is of no consequence: the module is fetched again, and reported on
+ // then, when the note type is actually displayed.
+ void Promise.resolve(TYPE_MAPPINGS[noteType].view()).catch(() => {});
+ }
+ });
+}
+
+/**
+ * Runs the callback once the browser is idle, or after a short delay where the browser has no notion
+ * of idleness (older Safari / WebKit). The timeout keeps the work from being put off indefinitely on
+ * a page that never goes idle.
+ */
+function whenIdle(callback: () => void) {
+ if (typeof requestIdleCallback === "function") {
+ requestIdleCallback(callback, { timeout: 5_000 });
+ } else {
+ setTimeout(callback, 1_000);
+ }
+}