CSS-in-JS

Some CSS-in-JS tools allows you to collect the page's styles while server-side rendering the page to HTML.

This enables you to add the styles to the rendered HTML, so that the browser loads the styles before loading JavaScript.

// /renderer/+onRenderHtml.jsx
 
import ReactDOMServer from "react-dom/server";
import React from "react";
import { escapeInject, dangerouslySkipEscape } from "vike/server";
import { CssCollector } from 'some-css-in-js-tool'
 
export { onRenderHtml };
 
async function onRenderHtml(pageContext) {
  const { Page } = pageContext;
  const page = <Page />;
 
  const collect = new CssCollector()
 
  const pageHtml = ReactDOMServer.renderToString(collect(page));
 
  // Vike inserts the `<script>` tags at the end of the HTML; the
  // browser will load the `<style>` tag first.
  return escapeInject`<!DOCTYPE html>
    <html>
      <head>
        <style>${dangerouslySkipEscape(collect.getCSS())}</style>
      </head>
      <body>
        <div id="page-view">${dangerouslySkipEscape(pageHtml)}</div>
      </body>
    </html>`;
}

See also