CSS must go through a relatively complex pipeline, just like HTML and JavaScript, the browser must download the file from the server, then parse it and apply it to the DOM. Due to the high degree of optimization, this process is usually very fast - for small web projects that are not based on frameworks, CSS usually accounts for only a small part of the total resource consumption.
Framework breaks this balance. Include a JavaScript GUI stack like jQuery UI and watch the CSS, JS and HTML sizes gradually increase. Typically, developers get stressed last, when they're behind a powerful 8-core workstation, using T3 internet, and no one cares about speed, which changes with the advent of latency or cpu-bound devices.
Optimizing CSS requires a multi-dimensional approach. While hand-written code can be simplified using various techniques, manually inspecting framework code is inefficient. In these cases, using automated simplification will produce better results.
The following steps will take us into the world of CSS optimization. Not every one of them will be directly applicable to your project, but be sure to keep them in mind.
01. Use abbreviations
Use abbreviation statements, as shown belowmargin
Statement can radically reduce the size of CSS files. A google search for CSS Shorthand
will reveal many other shorthand forms.
p { margin-top: 1px; margin-right: 2px; margin-bottom: 3px; margin-left: 4px; } p { margin: 1px 2px 3px 4px; }
02. Find and delete unused CSS
Delete unnecessary parts of CSS, j will obviously speed up the loading of web pages. Google's Chrome browser has this functionality out of the box. Just go to View > Developer > Developer Tools and open the Sources tab in Recent Builds and then open the command menu. Then, select Show Coverage to highlight unused code on the current page in the Coverage analysis window, which is an eye-opener for you.
Open the Google Chrome development tools, select Coverage
next to Conlse
, you can see the unused CSS, click on the corresponding item and highlight it Eye-opening display of unused code on the current page:
03. Do it the easier way
Navigating line-by-line analysis is not necessarily convenient. Using Google Chrome’s Audits can quickly help us analyze, use, and open the developer tools. Click the Audits
field and click Run audits to start analyzing the results.
04. Be aware of these issues
Remember that automatic analysis of CSS will always result in errors. After replacing uncompressed CSS files with compressed CSS files, test the entire site thoroughly - no one knows what errors the optimizer may cause.
05. Inline critical CSS
Loading external stylesheets takes time due to latency - therefore, you can The most critical code bits are placed in head
. However, be sure not to overdo it and remember that the person performing the maintenance tasks must also read the code.
<style> .blue{color:blue;} </style> <p> Hello, world! </p>
06. Allow anti-parallel parsing
##@import Conveniently add CSS styles to the code. Unfortunately, these benefits don't come without a price: since
@import can be nested, they cannot be parsed in parallel. A more parallel approach is to use a series of
<link> tags, which the browser can fetch immediately.
@import url("a.css"); @import url("b.css"); @import url("c.css"); <link> <link> <link>
07. Replace images with CSS
A few years ago, a set of translucent pngs was commonplace to create translucent effects on websites of. Now, CSS filters provide a resource-saving alternative. For example, the following code snippet ensures that the image in question appears as a grayscale version of itself.img { -webkit-filter: grayscale(100%); /* old safari */ filter: grayscale(100%); }
08. Use color shortcuts
Common sense tells us that a six-digit color descriptor is the most efficient way to express a color. This is not the case - in some cases, shorthand descriptions or color names can be shorter.target { background-color: #ffffff; } target { background: #fff; }
09. Remove unnecessary zeros and units
CSS 支持多种单位和数字格式。它们是一个值得感谢的优化目标——可以删除尾随和跟随的零,如下面的代码片段所示。此外,请记住,零始终是零,添加维度不会为包含的信息附带价值。
padding: 0.2em; margin: 20.0em; avalue: 0px; padding: .2em; margin: 20em; avalue: 0;
10. 消除过多分号
这种优化需要谨慎,因为它会影响代码的更改。CSS的规范允许省略属性组中的最后一个分号。由于这种优化方法所节省的成本很小,所以我们主要针对那些正在开发自动优化的程序员说明这一点。
p { . . . font-size: 1.33em }
11.使用纹理图集
由于协议开销的原因,加载多个小图片的效率很低。CSS 精灵将一系列小图片组合成一个大的PNG 文件,然后通过 CSS 规则将其分解。TexturePacker 等程序大大简化了创建过程。
.download { width:80px; height:31px; background-position: -160px -160px } .download:hover { width:80px; height:32px; background-position: -80px -160px }
12. 省略 px
提高性能的一个简单方法是使用CSS标准的一个特性。为 0 的数值默认单位是 px
—— 删除 px
可以为每个数字节省两个字节。
h2 {padding:0px; margin:0px;} h2 {padding:0; margin:0}
13. 避免需要性能要求的属性
分析表明,一些标签比其他标签更昂贵。以下这些解析会影响性能—如果在没有必要的情况,尽量不要使用它们。
border-radius box-shadow transform filter :nth-child position: fixed;
14. 删除空格
空格——考虑制表符、回车符和空格——使代码更容易阅读,但从解析器的角度看,它没有什么用处。在发布前删除它们,更好的方法是将此任务委托给 shell 脚本或类似的工具。
15. 删除注释
注释对编译器也没有任何作用。创建一个自定义解析器,以便在发布之前删除它们。这不仅节省了带宽,而且还确保攻击者和克隆者更难理解手头代码背后的思想。
16. 使用自动压缩
Yahoo 的用户体验团队创建了一个处理许多压缩任务的应用程序。它以 JAR 文件的形式发布,在这里可用,并且可以使用所选的JVM运行。
java -jar yuicompressor-x.y.z.jar Usage: java -jar yuicompressor-x.y.z.jar [options] [input file] Global Options -h, --help Displays this information --type <js> Specifies the type of the input file</js>
17. 在 NPM 运行它
如果你希望将产品集成到 Node.JS 中,请访问 npmjs.com/package/yuicompressor。维护不良的存储库包含一组包装器文件和JavaScript API。
var compressor = require('yuicompressor'); compressor.compress('/path/to/ file or String of JS', { //Compressor Options: charset: 'utf8', type: 'js',
18. 保持 Sass 的检查
虽然 CSS 选择器的性能不像几年前那么重要(请参阅参考资料),但是像 Sass 这样的框架有时会产生非常复杂的代,不时查看输出文件,并考虑优化结果的方法。
19. 设置缓存
有句老话说,最快的文件永远不会通过网络发送。让浏览器缓存请求有效地实现这一点。遗憾的是,缓存头的设置必须在服务器上进行。充分上面讲的的两个 Chrome 工具,它们提供了一种快速分析更改结果的方法。
20. 打破缓存
设计人员通常不喜欢缓存,因为他们担心浏览器会缓存上次的样式表。解决这个问题的一个简单方法是包含带有文件名的标记。遗憾的是,由于一些代理拒绝缓存具有“动态”路径的文件,此步骤所附带的代码中概述的方案并不适用于所有地方。
<link>
21. 不要忘记基础知识
优化CSS只是游戏的一部分。如果你的服务器不使用 HTTP/2 和 gzip 压缩,那么在数据传输期间会损失很多时间。幸运的是,解决这两个问题通常很简单。我们的示例显示了对常用Apache 服务器的一些调整。如果您发现自己在一个不同的系统上,只需参考服务器文档即可。
pico /etc/httpd/conf/httpd.conf AddOutputFilterByType DEFLATE text/html AddOutputFilterByType DEFLATE text/css
推荐学习:CSS视频教程
The above is the detailed content of CSS performance optimization methods worth collecting. For more information, please follow other related articles on the PHP Chinese website!