Skip to content

Critical CSS for SvelteKit

Markdown
Loading…

Paint the banner on the first frame by inlining its rules in the HTML.

What it does

cookieyesHandle does all of this for you; there is nothing to set up beyond the stylesheet route from Installation. The rest of the page explains what it does.

The normal stylesheet import puts the stylesheet on the critical path: the browser waits for it before painting anything. On a slow connection that delay is longer than everything else the SDK does. critical.css is the small part of the stylesheet that paints the banner; put it inline in <head> and load the full stylesheet without blocking, and the banner is styled on the first frame.

FileContentsSize
styles.cssEverything: banner, dialogs, toggles, recall button, reload noticeabout 3.8 KB gzipped
critical.cssOnly what the banner needs to paintabout 1.8 KB gzipped

Set it up

Nothing to do. On every page the handle writes critical.css inline right after <meta charset>, ahead of every other tag in <head>, and links the full stylesheet so it loads without blocking; the SDK switches it on once it starts. The stylesheet route serves it at /cookieyes/styles.css, under your app's base path, compressed and cached for a year under a versioned address:

src/routes/cookieyes/styles.css/+server.ts
export { GET } from "@cookieyes/sveltekit/styles-route";

To mount the route at another path, move the file there and set stylesHref on the handle:

src/hooks.server.ts
import { cookieyesHandle } from "@cookieyes/sveltekit";
import { config } from "./lib/cookieyes";

export const handle = cookieyesHandle({ ...config, stylesHref: "/assets/cookieyes.css" });

The tags are written into the HTML SvelteKit sends, so they are also there on routes with ssr = false and on prerendered pages. In a build with no server, such as adapter-static, add export const prerender = true; to the stylesheet route so it is written as a file.

If you send a Content-Security-Policy, the inline block needs its hash in style-src. See CSP.

Common mistakes

The preferences dialog is unstyled, the banner is fine. The full stylesheet did not load. In the Network tab, /cookieyes/styles.css, or your stylesHref, must return CSS.

Next steps

  • CSP: the style-src hash for the inline block

On this page