Is it possible to wait for Jinja2 to finish inserting all template elements before executing a certain script? I'm attempting to render some math using KaTeX on a page, that also contains a bunch of template blocks. However, the math is rendered before all of the template blocks are rendered by Jinja2, so any math in said blocks does not render.
I could set a timeout of, say, 5 seconds and execute the rendering script then (this works), but I'd rather use a more elegant solution. Using defer
inside the <script>
tags as instructed here does nothing, nor does
<script>
document.addEventListener("DOMContentLoaded", function() {
renderMathInElement(document.body, {
// ...options...
});
});
</script>
What is the event
that tells the browser a templating engine such as Jinja2 has finished its work? It certainly isn't DOMContentLoaded
, based on the above.
Edit
Here is an example course implemented using the A+ LMS. The troublesome template can be found in the folder _templates
. The default template uses MathJax, but since that particular library has some annoying features, such as being very slow when there is a lot of math to be rendered, I decided to use KaTeX instead. Here is my version of the template:
{% extends "aplus/layout.html" %}
{% block extrahead %}
<!-- MathJax (LaTex math)
<script type="text/javascript" async src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML" data-aplus></script>
-->
<!-- KaTeX (LaTeX math) -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.10.2/dist/katex.min.css" integrity="sha384-yFRtMMDnQtDRO8rLpMIKrtPCD5jdktao2TV19YiZYWMDkUR5GQZR/NOVTdquEx1j" crossorigin="anonymous" data-aplus>
<script defer type="text/javascript" src="https://cdn.jsdelivr.net/npm/katex@0.10.2/dist/katex.min.js" integrity="sha384-9Nhn55MVVN0/4OFx7EE5kpFBPsEMZxKTCnA+4fqDmg12eCTqGi6+BB2LjY8brQxJ" crossorigin="anonymous" onload="console.log('Hello, this is KaTeX!');" data-aplus></script>
<script data-aplus>
function render_katex() {
if (window.katex) {
renderMathInElement(document.body,{delimiters: [
{left: "\\[", right: "\\]", display: true},
{left: "\\(", right: "\\)", display: false}]}
);
console.log("Math rendered.");
} else {
console.log("KaTeX not loaded.")
};
};
</script>
<script defer type="text/javascript" src="https://cdn.jsdelivr.net/npm/katex@0.10.2/dist/contrib/auto-render.min.js" integrity="sha384-kWPLUVMOks5AQFrykwIup5lo0m3iMkkHrD0uJ4H5cjeGihAutqP0yW0J6dpFiVkI" crossorigin="anonymous" onload="setTimeout(render_katex,300);" data-aplus></script>
<!-- Custom course styles -->
<link rel="stylesheet"
href="{{ pathto('_static/course.css', 1) }}"
type="text/css"
data-aplus />
<link rel="stylesheet"
href="{{ pathto('_static/active_element.css', 1) }}"
type="text/css"
data-aplus />
{% endblock %}
Edit 2
A link to the full source of the page on Pastebin.