skip to Main Content

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.

enter image description here

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


  1. 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.

    if(/* content has math equation */) {
      conte Katex = (await import(/* path to the library */)).default;
    }

    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.

    import Head from 'next/head'
     
    function IndexPage() {
      return (
        <div>
          <Head>
            <title>My page title</title>
          </Head>
          <p>Hello world!</p>
        </div>
      )
    }
     
    export default IndexPage

    You can read more here.

    Login or Signup to reply.
  2. Have you checked this doc https://katex.org/docs/node?

    yarn add katex
    yarn build
    

    On your component import katex from ‘katex’;

    Then check https://katex.org/docs/api

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search