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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With