theKashey / used-styles

📝All the critical styles you've used to render a page.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Override inline styles

eseQ opened this issue · comments

Hello. I want to describe a simple case. Imagine:
Page on an initial state has simple div with class my-box and style

.my-box {
  margin: 0 auto;
}

We already get this style as critical in <style></style> tag.
Later we did API-request add '.extra-class' to our div with 'my-box' class.

.extra-class {
  margin: 10px 20px;
}

Now we have .my-box class in style tag with hight priority, .my-box and .extra-class in CSS file. And margin from .extra-class will be ignore.
Does exist some way to manage inline styles maybe? For ex:

  1. Prepare multiple style tags by getCriticalStyles split by source with data-used-styles
  2. Remove this style after load equal CSS file.

What kind of pitfalls did I miss?

No pitfalls. This is how it's working. That's why you have to moveStyles to hoist them on top, above any other CSS file, let those CSS files override critical styles:

import { moveStyles } from 'used-styles/moveStyles';
moveStyles();

I can`t understand. Can u provide more complete example? I use simple renderToString

Ok, so that's the problem - critical style extracting is working at the Server Side, but "fixture" is working on the client side.

You named two option:

  • Prepare multiple style tags by getCriticalStyles split by source with data-used-styles
  • Remove this style after load equal CSS file.

And there is 3rd option:

  • hosts (aka move) critical styles above the "real one" - that would fix style declaration ordering and let "real styles" override critical.

So what to do

  • on the client side, just after DOMReady/StyleDeclaration/WhenYouAreReady - moveStyles. That's all.

But how to detect when real style loading has been finished? We can have many different files with different weight who has different load time. Do we need to wait for all? Or can we use moveStyles after each load?

No, you are calling it once to move inlined styles above any "real" one.
You might remove all inlined styles when all real ones would load, but that's not required.

Oh ok got it. I just misunderstood. Simple tags order resolve this issue. I thought inlined style (in style tag) always has more priority than link tag.
Anyway, sorry for bothering you.

И спасибо за вклад в эту тему. Не так много людей, кто пишет на тему ssr и в частности потокового рендеренга.

🤘, I hope it would be useful for you. Don't forget to tell friends :)