structyl

Init Color Scheme Script

stable

Sets the initial color-scheme attribute before hydration.

Basic usage

Script injected into <head> before hydration:
var m = localStorage.getItem("structyl-mode") || "system";
if (m === "system") {
  m = matchMedia("(prefers-color-scheme: dark)").matches
    ? "dark" : "light";
}
document.documentElement.setAttribute("data-theme", m);

Examples

System mode default

defaultMode="system" reads prefers-color-scheme on first paint — no flash of wrong theme.

Generated inline script (runs before React hydrates):

var m = localStorage.getItem("structyl-mode") || "system";
if (m === "system") {
  m = matchMedia("(prefers-color-scheme: dark)").matches
    ? "dark" : "light";
}
document.documentElement
  .setAttribute("data-theme", m);

Custom attribute and storage key

Override the HTML attribute and localStorage key to match your existing theme system.

Script sets data-color-mode on <html>:

var m = localStorage.getItem("my-app-theme") || "light";
// ...
document.documentElement
  .setAttribute("data-color-mode", m);

Storage and attribute

Configure storageKey, defaultMode and attribute before hydration.

Place this script before app markup.

Features

  • LocalStorage-aware.
  • System mode support.

Installation

bash
pnpm dlx structyl add init-color-scheme-script

API Reference

InitColorSchemeScript

Initial color mode script.

PropTypeDefault
storageKeystring

LocalStorage key.

'structyl-mode'
defaultMode'light' | 'dark' | 'system'

Initial mode fallback.

'system'
attributestring

Document attribute to set.

'data-theme'
Init Color Scheme Script | structyl