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,7 +12,12 @@ 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
let str = this.element.textContent;
if(str.match(/(\$|\\\(|\\\[).+(\$|\\\)|\\\])/)) {
import('katex/dist/contrib/auto-render').then((autorender) => {
//This calls renderMathInElement()
autorender.default(this.element, {
delimiters: [ delimiters: [
{left: "$$", right: "$$", display: true}, {left: "$$", right: "$$", display: true},
{left: "$", right: "$", display: false}, {left: "$", right: "$", display: false},
@ -20,6 +25,9 @@ export default class extends Controller {
{left: "\\[", right: "\\]", display: true} {left: "\\[", right: "\\]", display: true}
] ]
}); });
})
}
} }
mutate() { mutate() {