cxs-css / cxs

fast af css-in-js in 0.7kb
MIT License
1.19k stars 68 forks source link

Rehydration #36

Open PepijnSenders opened 7 years ago

PepijnSenders commented 7 years ago

Hey guys, was wondering why you guys don't implement client rehydration like Aphrodite and Glamor do?

Isn't this a bit wasteful, since all the CSS is already generated?

PepijnSenders commented 7 years ago

Also I created a small blog post on this topic: https://engineering.hellofresh.com/the-css-in-js-battle-89c34a7a83ea

corysimmons commented 5 years ago

Thanks for linking to these. I think this lib had a ton of potential, but needs hydration/vendor prefixes to be viable for my use case anyway. :(

souporserious commented 2 years ago

If anyone comes across this issue, I wrote a simple rehydration script if you're using a fork of cxs like I am:

export function hydrateCss() {
  if (typeof document === 'undefined') {
    return
  }

  const styleElement = document.getElementById(
    STYLE_ID
  ) as HTMLStyleElement

  if (styleElement === null) {
    return
  }

  const sheet = styleElement.sheet!
  const rules = sheet.cssRules
  const maxLength = rules.length - 1

  for (let index = maxLength; index >= 0; index--) {
    const rule = rules[index]
    const className = rule.cssText.split(' ')[0].slice(1)
    const declaration = rule.cssText.slice(
      rule.cssText.indexOf('{') + 2,
      rule.cssText.lastIndexOf('}') - 2
    )
    const [key, value] = declaration.split(': ')
    const cacheKey = hash(key + value)

    insert(rule.cssText)

    cache[cacheKey] = className

    sheet.deleteRule(index)
  }
}

It only handles simple rules right now, but I plan to expand it to handle nested selectors and media queries when I get a chance.