I need to load Katex CSS to style math equations. I don’t know ahead of time exactly which pages need it (it depends on which users include math in their posts), but I do know which routes might need it.
For more context, here’s a page with math and here’s one without math.
Currently, I’m loading the CSS using a <link>
tag in the header of my root layout, like this.
// src/app/layout.jsx
export default async function RootLayout({ children }) {
return (
<html suppressHydrationWarning lang="en">
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css" />
</head>
<body>
<main>
{ children }
</main>
</body>
</html>
)
}
This strategy makes it a “render blocking resource” as you can see from my lighthouse report.
If it’s possible, I would prefer to load the CSS lazily AND dynamically, depending on if the current page has math that needs styling.
I’ve read the docs on CSS and lazy loading, but I’m still scratching my head on how to accomplish this.