是否值得删除未使用的CSS?

Joh*_*ohn 0 css gulp

我正在与2位其他大学开发人员一起开发一个简单的Web应用程序。我们正在使用几个库和包。我现在正在尝试准备好我们的应用程序以进行部署,但是注意到它的运行速度很慢。有很多未使用的CSS规则。

我尝试手动浏览编译的样式,搜索引用并删除。但这确实很乏味。

我的问题是:

  • 删除未使用的CSS规则是否值得,或者结果可以忽略不计?
  • 如何做到这一点的最佳方法是什么?

Ali*_*cia 5

是否值得删除未使用的CSS规则?

我会说是的。在生产版本中包含任何未使用的代码并不好。

但是,除非出了点大错,否则CSS加载缓慢是页面加载缓慢的原因,实际上,加载几页未使用的CSS规则的影响几乎可以忽略。图像/媒体,或者脚本更像是礼节。

您可能应该调查导致网页变慢的原因。查看开发人员工具的网络标签,开始调试为什么页面加载速度缓慢,Google Page Load Insights也可能会有所帮助。看看这个博客系列,有关如何也加快您的Web应用程序的速度。

If you've not done so already you should probably minify and bundle your CSS and JS for production also.


How to find and remove unused CSS rules

Removing unused CSS is a common task, and there are a lot of packages and tools out there which make it strait-forward. There are several options, going forwards:

1. Manually remove unused CSS.

If your app is still quite small, this will probably be the easiest approach.

  1. Open Chrome DevTools
  2. Open the command menu with: cmd + shift + p
  3. Type in “Coverage” and click on the “Show Coverage” option
  4. Select a CSS file from the Coverage tab which will open the file up in the Sources tab

Source: Google Developer, Chrome 59

2. Use an online tool

There are tools out there, where you can just feed it a link to your site, and it will search and find unused CSS. The drawback here, is that this won't work locally.

  • The best tool available it probably UnusedCSS, however it only allows you to do one site for free.
  • UnCSS it totally free, but not as comprehensive.
  • PureifyCSS is also good, and free.

3. Automate CSS removal

uncss allows you to automate unused CSS removal, either at built-time, or complile-time. It also works with Grunt and Babel.


A word of warning, some of your CSS might be detected as unused, when actually you are using it later on, such as when a request has finished loading. Be sure not to delete classes that are indirectly used.

Edit:

Be careful when using coverage for CSS usage, it considers media queries, hover effects and others as useless since they're not applied when loading your page

See also: https://css-tricks.com/unused/

  • 在使用CSS覆盖率时要小心,因为它将媒体查询,悬停效果和其他因素视为无用,因为在加载页面时未应用它们。 (3认同)