I am currently trying to make a website where different codes are loaded in at different times. However the content of these codes are stored in a JSON file and are loaded in to the page through JS.
Prism.js seems to run syntax highlighting at load time and I would like to run syntax highlighting on the code after it has been loaded from the JS.
Is there any way I can do this using Prism?
You should be able to call one of highlightAll()
, highlightAllUnder()
or highlightElement()
after the content has been loaded to highlight them:
setTimeout(
() => {
document.body.insertAdjacentHTML(
'beforeend',
'<pre><code class="language-css">.async-loaded { color: red }</code></pre>',
);
window.Prism.highlightAll();
},
1000
);
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism.min.css" integrity="sha512-tN7Ec6zAFaVSG3TpNAKtk4DOHNpSwKHxxrsiw4GHKESGPs5njn/0sMCUMl2svV4wo4BK/rCP7juYz+zx+l6oeQ==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/prism.min.js" integrity="sha512-7Z9J3l1+EYfeaPKcGXu3MS/7T+w19WtKQY/n+xzmw4hZhJ9tyYmcUS+4QqAlzhicE5LAfMQSF3iFTK9bQdTxXg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/plugins/autoloader/prism-autoloader.min.js" integrity="sha512-SkmBfuA2hqjzEVpmnMt/LINrjop3GKWqsuLSSB3e7iBmYK7JuWw4ldmmxwD9mdm2IRTTi0OxSAfEGvgEi0i2Kw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<pre><code class="language-css">.pre-loaded { color: green }</code></pre>