Why extract css
Asked Answered
H

1

11

I'm building a single page app using webpack. Have seen several times that it is recommended to extract css from production build but didn't find the reason.

Could anyone explain why it is treated as a best practice and what the advantages of that for production?

Is it needed for caching styles and js separately on client only or there are other reasons, cons, pros?

An example of such recommendation you can find by link below

https://github.com/webpack-contrib/sass-loader

In production

Usually, it's recommended to extract the style sheets into a dedicated file in production using the ExtractTextPlugin. This way your styles are not dependent on JavaScript:

Hocus answered 14/4, 2017 at 19:7 Comment(2)
This way your styles are not dependent on JavaScriptIndelicate
@Indelicate I see these words but they don't describe the reason only result. The question is 'why it is recommended? what are advantages of such approach?'Hocus
G
17

It is recommended mostly because of two reasons that are enough to follow the practice:

1) The extracted css stylesheets can be cached separately. Therefore if your app code changes, the browser can only fetch the JS files that changed.

2) Without extracting css you may suffer from Flash of Unstyled Content (FUOC). The browser must fully interpret javascript to apply styles to your page which can cause FUOC (and likely will). It always takes a while, and only then the styles will be applied. By extracting css you allow the browser to handle the styles separately, preferably before interpreting JS (load css before js) and eliminate FUOC.

On the other hand, as Oscar suggested in the comments the advantage of leaving CSS combined with JS could be when you are developing an npm package with styles and consumers of that library wouldn't need to add a separate reference to stylesheets.

Galingale answered 15/4, 2017 at 8:55 Comment(2)
The advantage may be when you are developing npm package with styles and consumer of that library wouldn't need to add separate reference to stylesheetsDena
AKA FOBUC (Flash of Butt Ugly Content)Gower

© 2022 - 2024 — McMap. All rights reserved.