Skip to content

Commit 5be7cb2

Browse files
committed
katex, embed-resources - script that loads katex when embed-resources needs to be context aware of require conflict
- Require.js being loaded will trigger AMD detection for KaTeX, which prevents `widow.katex` to be defined - About KaTeX in browser: https://katex.org/docs/browser#module-loaders - About AMD in JS: https://github.com/amdjs/amdjs-api/wiki/AMD#defineamd-property-
1 parent e67ce56 commit 5be7cb2

1 file changed

Lines changed: 32 additions & 11 deletions

File tree

src/command/render/template.ts

Lines changed: 32 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -270,26 +270,47 @@ function katexScript(url: string) {
270270
link.rel = "stylesheet";
271271
link.href = "${url}katex.min.css";
272272
head.appendChild(link);
273-
274-
var script = document.createElement("script");
275-
script.type = "text/javascript";
276-
script.src = "${url}katex.min.js";
277-
script.async = false;
278-
script.addEventListener('load', function() {
273+
274+
function renderMathElements() {
279275
var mathElements = document.getElementsByClassName("math");
280-
var macros = [];
281-
for (var i = 0; i < mathElements.length; i++) {
282-
var texText = mathElements[i].firstChild;
283-
if (mathElements[i].tagName == "SPAN") {
276+
var macros = [];
277+
for (var i = 0; i < mathElements.length; i++) {
278+
var texText = mathElements[i].firstChild;
279+
if (mathElements[i].tagName == "SPAN") {
280+
if (window.katex) {
284281
window.katex.render(texText.data, mathElements[i], {
285282
displayMode: mathElements[i].classList.contains('display'),
286283
throwOnError: false,
287284
macros: macros,
288285
fleqn: false
289286
});
287+
} else {
288+
console.error("KaTeX has not been loaded correctly, as not found globally.");
290289
}
291290
}
292-
});
291+
}
292+
}
293+
294+
var script = document.createElement("script");
295+
script.src = "${url}katex.min.js";
296+
script.onload = renderMathElements;
297+
298+
// Check for RequireJS and AMD detection as it conflicts with KaTeX loading.
299+
if (typeof require === 'function' && typeof define === 'function' && define.amd) {
300+
// Disable require.js AMD detection temporarily, as it conflicts with KaTeX loading using CommonJS
301+
var disableAmdScript = document.createElement("script");
302+
disableAmdScript.textContent = 'window._amd_backup = window.define.amd; window.define.amd = false;';
303+
head.appendChild(disableAmdScript);
304+
305+
// overwrite onload to restore Require.js AMD detection
306+
script.onload = function() {
307+
// Restore Require.js AMD detection
308+
window.define.amd = window._amd_backup;
309+
delete window._amd_backup;
310+
renderMathElements();
311+
};
312+
}
313+
293314
head.appendChild(script);
294315
});
295316
</script>

0 commit comments

Comments
 (0)