为什么要提取css [英] Why extract css

查看:73
本文介绍了为什么要提取css的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 webpack 构建一个单页应用程序.看到好几次建议从生产构建中提取css但没有找到原因.

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?

是否需要仅在客户端单独缓存样式和 js 或有其他原因、缺点、优点?

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

生产中

通常,建议使用 ExtractTextPlugin 将样式表提取到生产中的专用文件中.这样你的样式就不会依赖于 JavaScript:

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) 提取的 css 样式表可以单独缓存.因此,如果您的应用代码发生变化,浏览器只能获取发生变化的 JS 文件.

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) 如果不提​​取 css,您可能会遇到无样式内容 (FUOC) 闪烁.浏览器必须完全解释 javascript 才能将样式应用于您的页面,这可能会导致 FUOC(并且可能会).这总是需要一段时间,然后才会应用样式.通过提取 css,您可以让浏览器单独处理样式,最好在解释 JS 之前 (在js之前加载css)并消除FUOC.

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.

另一方面,正如 Oscar 在评论中所建议的,将 CSS 与 JS 结合使用的优势可能在于,当您开发具有样式的 npm 包时,该库的使用者无需添加对样式表的单独引用.

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.

这篇关于为什么要提取css的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆