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.
2
Answers
You can use the
import
function.So first you can check whether the content has ant math equation or not and if it has, you’ll import your library dynamically.
You can read more here.
And also you can use the
Head
component which lets you to add your desired meta tags in the html.You can read more here.
Have you checked this doc https://katex.org/docs/node?
On your component import katex from ‘katex’;
Then check https://katex.org/docs/api