Lazy load the katex library if latex content is really present

This commit is contained in:
Jan Böhmer 2022-03-06 16:09:24 +01:00
parent cef74ff35a
commit f1ea25cad2

View file

@ -1,10 +1,10 @@
import {Controller} from "@hotwired/stimulus"; import {Controller} from "@hotwired/stimulus";
import "katex"; //import "katex";
import 'katex/dist/katex.css'; import 'katex/dist/katex.css';
import renderMathInElement from "katex/dist/contrib/auto-render"; import {auto} from "@popperjs/core";
//import renderMathInElement from "katex/dist/contrib/auto-render";
/* stimulusFetch: 'lazy' */
export default class extends Controller { export default class extends Controller {
connect() { connect() {
this.applyLatex(); this.applyLatex();
@ -12,14 +12,22 @@ export default class extends Controller {
} }
applyLatex() { applyLatex() {
renderMathInElement(this.element, { //Only import the katex library, if we have an delimiter string in our element text
delimiters: [ let str = this.element.textContent;
{left: "$$", right: "$$", display: true}, if(str.match(/(\$|\\\(|\\\[).+(\$|\\\)|\\\])/)) {
{left: "$", right: "$", display: false}, import('katex/dist/contrib/auto-render').then((autorender) => {
{left: "\\(", right: "\\)", display: false}, //This calls renderMathInElement()
{left: "\\[", right: "\\]", display: true} autorender.default(this.element, {
] delimiters: [
}); {left: "$$", right: "$$", display: true},
{left: "$", right: "$", display: false},
{left: "\\(", right: "\\)", display: false},
{left: "\\[", right: "\\]", display: true}
]
});
})
}
} }
mutate() { mutate() {