@@ -55,6 +55,8 @@ export default class MultipleChoice extends HTMLElement {
5555 this . _keyboardEventsEnabled = false ;
5656 this . _audioInitialized = false ;
5757 this . _root = null ;
58+ this . _mathObserver = null ;
59+ this . _mathRenderPending = false ;
5860
5961 this . _rerender = debounce (
6062 ( ) => {
@@ -75,15 +77,12 @@ export default class MultipleChoice extends HTMLElement {
7577 this . setAttribute ( 'role' , 'region' ) ;
7678 this . setLangAttribute ( ) ;
7779
80+ this . _initMathObserver ( ) ;
81+
7882 if ( ! this . _root ) {
7983 this . _root = createRoot ( this ) ;
8084 }
8185 this . _root . render ( element ) ;
82- // Use requestAnimationFrame to ensure DOM is fully painted before rendering math
83- requestAnimationFrame ( ( ) => {
84- log ( 'render complete - render math' ) ;
85- renderMath ( this ) ;
86- } ) ;
8786
8887 if ( this . _model . keyboardEventsEnabled === true && ! this . _keyboardEventsEnabled ) {
8988 this . enableKeyboardEvents ( ) ;
@@ -120,6 +119,38 @@ export default class MultipleChoice extends HTMLElement {
120119 ) ;
121120 }
122121
122+ _scheduleMathRender = ( ) => {
123+ if ( this . _mathRenderPending ) return ;
124+ this . _mathRenderPending = true ;
125+
126+ requestAnimationFrame ( ( ) => {
127+ if ( this . _mathObserver ) {
128+ this . _mathObserver . disconnect ( ) ;
129+ }
130+ log ( 'render complete - render math' ) ;
131+ renderMath ( this ) ;
132+ this . _mathRenderPending = false ;
133+ setTimeout ( ( ) => {
134+ if ( this . _mathObserver ) {
135+ this . _mathObserver . observe ( this , { childList : true , subtree : true } ) ;
136+ }
137+ } , 50 ) ;
138+ } ) ;
139+ } ;
140+
141+ _initMathObserver ( ) {
142+ if ( this . _mathObserver ) return ;
143+ this . _mathObserver = new MutationObserver ( this . _scheduleMathRender ) ;
144+ this . _mathObserver . observe ( this , { childList : true , subtree : true } ) ;
145+ }
146+
147+ _disconnectMathObserver ( ) {
148+ if ( this . _mathObserver ) {
149+ this . _mathObserver . disconnect ( ) ;
150+ this . _mathObserver = null ;
151+ }
152+ }
153+
123154 onShowCorrectToggle ( ) {
124155 renderMath ( this ) ;
125156 }
@@ -192,6 +223,7 @@ export default class MultipleChoice extends HTMLElement {
192223 }
193224
194225 connectedCallback ( ) {
226+ this . _initMathObserver ( ) ;
195227 this . _rerender ( ) ;
196228
197229 // Observation: audio in Chrome will have the autoplay attribute,
@@ -281,6 +313,7 @@ export default class MultipleChoice extends HTMLElement {
281313 }
282314
283315 disconnectedCallback ( ) {
316+ this . _disconnectMathObserver ( ) ;
284317 if ( this . _keyboardEventsEnabled ) {
285318 window . removeEventListener ( 'keydown' , this . _boundHandleKeyDown ) ;
286319 this . _keyboardEventsEnabled = false ;
0 commit comments