perf: cache KaTeX module import as singleton across all renderer instances (#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
This commit is contained in:
@@ -1,5 +1,21 @@
|
|||||||
<script lang="ts">
|
<script lang="ts" context="module">
|
||||||
import type { renderToString as katexRenderToString } from 'katex';
|
import type { renderToString as katexRenderToString } from 'katex';
|
||||||
|
|
||||||
|
// Module-level singleton: load katex once, share across all KatexRenderer instances
|
||||||
|
let katexRenderer: Promise<typeof katexRenderToString> | null = null;
|
||||||
|
function getKatexRenderer(): Promise<typeof katexRenderToString> {
|
||||||
|
if (!katexRenderer) {
|
||||||
|
katexRenderer = Promise.all([
|
||||||
|
import('katex'),
|
||||||
|
import('katex/contrib/mhchem'),
|
||||||
|
import('katex/dist/katex.min.css')
|
||||||
|
]).then(([katex]) => katex.renderToString);
|
||||||
|
}
|
||||||
|
return katexRenderer;
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<script lang="ts">
|
||||||
import { onMount } from 'svelte';
|
import { onMount } from 'svelte';
|
||||||
|
|
||||||
export let content: string;
|
export let content: string;
|
||||||
@@ -8,15 +24,11 @@
|
|||||||
let renderToString: typeof katexRenderToString | null = null;
|
let renderToString: typeof katexRenderToString | null = null;
|
||||||
|
|
||||||
onMount(async () => {
|
onMount(async () => {
|
||||||
const [katex] = await Promise.all([
|
renderToString = await getKatexRenderer();
|
||||||
import('katex'),
|
|
||||||
import('katex/contrib/mhchem'),
|
|
||||||
import('katex/dist/katex.min.css')
|
|
||||||
]);
|
|
||||||
renderToString = katex.renderToString;
|
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
{#if renderToString}
|
{#if renderToString}
|
||||||
{@html renderToString(content, { displayMode, throwOnError: false })}
|
{@html renderToString(content, { displayMode, throwOnError: false })}
|
||||||
{/if}
|
{/if}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user