1- /* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment */
1+ /* eslint-disable */
22
33export abstract class BaseMathJaxHelper {
44 protected abstract cdnUrl : string ;
55 protected mathjax : any ;
6-
7- private renderQueue : Promise < void > = Promise . resolve ( ) ;
6+ private loadPromise : Promise < void > | null = null ;
87
98 /**
109 * MathJax helper.
@@ -16,12 +15,16 @@ export abstract class BaseMathJaxHelper {
1615 }
1716
1817 /**
19- * Loads MathJax from a CDN.
18+ * Loads MathJax from a CDN and initializes it .
2019 *
2120 * @protected
2221 */
2322 protected loadFromCdn ( ) : Promise < void > {
24- return new Promise ( ( resolve , reject ) => {
23+ if ( this . loadPromise ) {
24+ return this . loadPromise ;
25+ }
26+
27+ return this . loadPromise = new Promise ( ( resolve , reject ) => {
2528 const script = document . createElement ( "script" ) ;
2629 script . type = "text/javascript" ;
2730 script . src = this . cdnUrl ;
@@ -30,7 +33,9 @@ export abstract class BaseMathJaxHelper {
3033 script . onload = ( ) => {
3134 // @ts -expect-error After loading the script, window.MathJax will exist.
3235 this . mathjax = window . MathJax ;
33- resolve ( ) ;
36+
37+ // We return the startup promise to ensure that MathJax is fully initialized before using it.
38+ resolve ( this . mathjax . startup . promise ) ;
3439 } ;
3540 script . onerror = ( ) => reject ( new Error ( `Failed to load ${ this . cdnUrl } .` ) ) ;
3641
@@ -49,13 +54,9 @@ export abstract class BaseMathJaxHelper {
4954 * Renders LaTeX inside an element. Loads MathJax from a CDN if necessary.
5055 */
5156 render ( element : Element , inline : boolean ) : Promise < void > {
52- // We do this to chain every render call. This also ensures that we only load once from the CDN:
53- // https://docs.mathjax.org/en/v3.2-latest/web/typeset.html#handling-asynchronous-typesetting
54- return ( this . renderQueue = this . renderQueue . then ( ( ) => {
55- if ( this . mathjax === undefined ) {
56- return this . loadFromCdn ( ) . then ( ( ) => this . _render ( element , inline ) ) ;
57- }
58- return this . _render ( element , inline ) ;
59- } ) ) ;
57+ if ( this . mathjax === undefined ) {
58+ return this . loadFromCdn ( ) . then ( ( ) => this . _render ( element , inline ) ) ;
59+ }
60+ return this . _render ( element , inline ) ;
6061 }
6162}
0 commit comments