Skip to content

Build your personal knowledge base with Trilium Notes

perf(client): load KaTeX lazily

Elian Doran658ebae1320e
diff --git a/apps/client/src/services/content_renderer_text.ts b/apps/client/src/services/content_renderer_text.ts
index 4362d2a28e..03b39ee6fa 100644
--- a/apps/client/src/services/content_renderer_text.ts
+++ b/apps/client/src/services/content_renderer_text.ts
@@ -5,7 +5,6 @@ import froca from "./froca.js";
import { t } from "./i18n.js";
import link from "./link.js";
import { applyLinkEmbeds } from "./link_embed.js";
-import { renderMathInElement } from "./math.js";
import { getMermaidConfig, loadElkIfNeeded, postprocessMermaidSvg } from "./mermaid.js";
import { sanitizeNoteContentHtml } from "./sanitize_content.js";
import { formatCodeBlocks } from "./syntax_highlight.js";
@@ -41,6 +40,8 @@ export async function postProcessRichContent(note: FNote | FAttachment, $rendere
}
if ($renderedContent.find("span.math-tex").length > 0) {
+ // KaTeX is heavy, so the math service is only loaded when there are formulas to render.
+ const { renderMathInElement } = await import("./math.js");
renderMathInElement($renderedContent[0], { trust: true });
}
diff --git a/apps/client/src/widgets/dialogs/revisions.tsx b/apps/client/src/widgets/dialogs/revisions.tsx
index e39bfa4ba4..c3d13fab25 100644
--- a/apps/client/src/widgets/dialogs/revisions.tsx
+++ b/apps/client/src/widgets/dialogs/revisions.tsx
@@ -13,7 +13,6 @@ import FNote from "../../entities/fnote";
import dialog from "../../services/dialog";
import froca from "../../services/froca";
import { t } from "../../services/i18n";
-import { renderMathInElement } from "../../services/math";
import open from "../../services/open";
import options from "../../services/options";
import protected_session_holder from "../../services/protected_session_holder";
@@ -577,7 +576,12 @@ function RevisionContentText({ content }: { content: string | Uint8Array | undef
const contentRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (contentRef.current?.querySelector("span.math-tex")) {
- renderMathInElement(contentRef.current, { trust: true });
+ // KaTeX is heavy, so the math service is only loaded when there are formulas to render.
+ void import("../../services/math").then(({ renderMathInElement }) => {
+ if (contentRef.current) {
+ renderMathInElement(contentRef.current, { trust: true });
+ }
+ });
}
}, [content]);
return <RawHtmlBlock containerRef={contentRef} className="ck-content" html={sanitizeNoteContentHtml(content as string)} />;
diff --git a/apps/client/src/widgets/react/hooks.tsx b/apps/client/src/widgets/react/hooks.tsx
index a4a8cfb07e..098edeb0ac 100644
--- a/apps/client/src/widgets/react/hooks.tsx
+++ b/apps/client/src/widgets/react/hooks.tsx
@@ -15,7 +15,6 @@ import attributes from "../../services/attributes";
import froca from "../../services/froca";
import keyboard_actions from "../../services/keyboard_actions";
import { parseNavigationStateFromUrl, ViewScope } from "../../services/link";
-import math from "../../services/math";
import options, { type OptionValue } from "../../services/options";
import protected_session_holder from "../../services/protected_session_holder";
import server from "../../services/server";
@@ -1595,32 +1594,36 @@ export function useMathRendering(containerRef: RefObject<HTMLElement>, deps: unk
useEffect(() => {
if (!containerRef.current) return;
const mathElements = containerRef.current.querySelectorAll(".math-tex");
-
- for (const mathEl of mathElements) {
- // Skip if already rendered by KaTeX
- if (mathEl.querySelector(".katex")) continue;
-
- try {
- // CKEditor's data format wraps the equation with \(...\) or \[...\]
- // delimiters. katex.render() expects raw LaTeX without them.
- const raw = mathEl.textContent?.trim() ?? "";
- let equation: string;
- let displayMode = false;
-
- if (raw.startsWith("\\(") && raw.endsWith("\\)")) {
- equation = raw.slice(2, -2);
- } else if (raw.startsWith("\\[") && raw.endsWith("\\]")) {
- equation = raw.slice(2, -2);
- displayMode = true;
- } else {
- equation = raw;
+ if (!mathElements.length) return;
+
+ // KaTeX is heavy, so the math service is only loaded once there are equations to render.
+ void import("../../services/math").then(({ default: math }) => {
+ for (const mathEl of mathElements) {
+ // Skip if already rendered by KaTeX
+ if (mathEl.querySelector(".katex")) continue;
+
+ try {
+ // CKEditor's data format wraps the equation with \(...\) or \[...\]
+ // delimiters. katex.render() expects raw LaTeX without them.
+ const raw = mathEl.textContent?.trim() ?? "";
+ let equation: string;
+ let displayMode = false;
+
+ if (raw.startsWith("\\(") && raw.endsWith("\\)")) {
+ equation = raw.slice(2, -2);
+ } else if (raw.startsWith("\\[") && raw.endsWith("\\]")) {
+ equation = raw.slice(2, -2);
+ displayMode = true;
+ } else {
+ equation = raw;
+ }
+
+ math.render(equation, mathEl as HTMLElement, { displayMode });
+ } catch (e) {
+ console.warn("Failed to render math:", e);
}
-
- math.render(equation, mathEl as HTMLElement, { displayMode });
- } catch (e) {
- console.warn("Failed to render math:", e);
}
- }
+ });
}, deps); // eslint-disable-line react-hooks/exhaustive-deps
}
diff --git a/apps/client/src/widgets/toc.ts b/apps/client/src/widgets/toc.ts
index 16648c3fec..15358135aa 100644
--- a/apps/client/src/widgets/toc.ts
+++ b/apps/client/src/widgets/toc.ts
@@ -19,7 +19,6 @@ import RightPanelWidget from "./right_panel_widget.js";
import options from "../services/options.js";
import OnClickButtonWidget from "./buttons/onclick_button.js";
import appContext, { type EventData } from "../components/app_context.js";
-import katex from "../services/math.js";
import type FNote from "../entities/fnote.js";
import DOMPurify, { type Config as DOMPurifyConfig } from "dompurify";
@@ -274,7 +273,9 @@ export default class TocWidget extends RightPanelWidget {
let modifiedText = html;
if (matches.length > 0) {
- // Process all matches asynchronously
+ // KaTeX is heavy, so the math service is only loaded when there are formulas to render.
+ const { default: katex } = await import("../services/math.js");
+
for (const match of matches) {
let latexCode = match[1];
let rendered;
@@ -284,20 +285,8 @@ export default class TocWidget extends RightPanelWidget {
throwOnError: false
});
} catch (e) {
- if (e instanceof ReferenceError && e.message.includes("katex is not defined")) {
- // Load KaTeX if it is not already loaded
- try {
- rendered = katex.renderToString(latexCode, {
- throwOnError: false
- });
- } catch (renderError) {
- console.error("KaTeX rendering error after loading library:", renderError);
- rendered = match[0]; // Fall back to original if error persists
- }
- } else {
- console.error("KaTeX rendering error:", e);
- rendered = match[0]; // Fall back to original on error
- }
+ console.error("KaTeX rendering error:", e);
+ rendered = match[0]; // Fall back to original on error
}
// Replace the matched formula in the modified text