Home

Load the themed syntax highlighter

Most syntax highlighters are not compatible with both light and dark themes, so it's often necessary to load one when the theme changes.

🔗 index.html

<link id="prism" rel="stylesheet" href="/prism-coy.css">

🔗 script.js

let stylesheet = document.getElementById("prism");
function setTheme(isDark) {
  if (isDark) {
    stylesheet.setAttribute("href", "/prism-tomorrow.css");
  } else {
    stylesheet.setAttribute("href", "/prism-coy.css");
  }
}

🔗 For performance: preload

We can leverage the preload rel type to have both stylesheets ready as the page renders. This prevents the light syntax color scheme from loading, then quickly flashing to the dark syntax color scheme once the JavaScript says to.
It's a two line change.
<link rel="preload" href="/prism-coy.css" as="style">
<link rel="preload" href="/prism-tomorrow.css" as="style">
<link id="prism" rel="stylesheet" href="/prism-coy.css">
Now when we set the href to either theme's stylesheet, we'll have it ready to go.