Skip to content

Commit 7ea6afd

Browse files
authored
perf: cache KaTeX module import as singleton across all renderer instances (open-webui#21880)
* perf: cache KaTeX module import as singleton across all renderer instances KatexRenderer.svelte dynamically imports katex, mhchem, and the CSS on every component mount. When a message contains multiple math expressions, this triggers redundant module resolution for each one. Move the import promise to a module-level singleton using Svelte's context='module' script block so it loads once and is shared across all KatexRenderer instances. * Update KatexRenderer.svelte
1 parent 4654ecb commit 7ea6afd

1 file changed

Lines changed: 19 additions & 7 deletions

File tree

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,21 @@
1-
<script lang="ts">
1+
<script lang="ts" context="module">
22
import type { renderToString as katexRenderToString } from 'katex';
3+
4+
// Module-level singleton: load katex once, share across all KatexRenderer instances
5+
let katexRenderer: Promise<typeof katexRenderToString> | null = null;
6+
function getKatexRenderer(): Promise<typeof katexRenderToString> {
7+
if (!katexRenderer) {
8+
katexRenderer = Promise.all([
9+
import('katex'),
10+
import('katex/contrib/mhchem'),
11+
import('katex/dist/katex.min.css')
12+
]).then(([katex]) => katex.renderToString);
13+
}
14+
return katexRenderer;
15+
}
16+
</script>
17+
18+
<script lang="ts">
319
import { onMount } from 'svelte';
420
521
export let content: string;
@@ -8,15 +24,11 @@
824
let renderToString: typeof katexRenderToString | null = null;
925
1026
onMount(async () => {
11-
const [katex] = await Promise.all([
12-
import('katex'),
13-
import('katex/contrib/mhchem'),
14-
import('katex/dist/katex.min.css')
15-
]);
16-
renderToString = katex.renderToString;
27+
renderToString = await getKatexRenderer();
1728
});
1829
</script>
1930

2031
{#if renderToString}
2132
{@html renderToString(content, { displayMode, throwOnError: false })}
2233
{/if}
34+

0 commit comments

Comments
 (0)