前端性能优化基础篇之css
使用合并和简写减少code size
以"background"为例:
.cls1 { background-image: url(a.png); background-position: 0px 0px; } .cls2 { background-image: url(a.png); background-position: 10px 0px; } /* 163Bytes */
使用合并:
.cls1, .cls2 { background-image: url(a.png); background-position: 0px 0px; } .cls2 { background-position: 10px 0px; } /* 135Bytes */
使用简写:
.cls1, .cls2 { background: url(a.png); } .cls2 { background-position: 10px 0; } /* 92Bytes */
使用 conditional comments 减少code冗余
为了使我们的页面能够兼容IE及其下的不同版本, 很多时候我们不得不写一些冗余的css. 一部分只是针对IE6, 一部分只是针对IE7等. 这将造成页面所加载的css对于当前浏览器并不一定都有用. 为此我们可以使用微软提供的条件注释来保证那些针对性的样式只在IE或对应的IE版本上才会被加载, 如:
<!--[if IE 6]> <link rel="stylesheet" type="text/css" href="css/ie6.css" /> <![endif]--> <!--[if IE 7]> <link rel="stylesheet" type="text/css" href="css/ie7.css" /> <![endif]-->
注意细节提高渲染效率
尽量使用高效匹配选择器 -- 每种选择器都有一个固有的效率, 从高到低依次如下:
1. id选择器(#myid)
2. 类选择器(.myclassname)
3. 标签选择器(div,h1,p)
4. 相邻选择器(h1 + p)
5. 子选择器(ul > li)
6. 后代选择器(li a)
7. 通配符选择器(*)
8. 属性选择器(a[rel="external"])
9. 伪类选择器(a:hover,li:nth-child)
减少选择器层次 -- 浏览器解析选择器遵循的原则是从右往左匹配. 因此匹配层次越少匹配越快, ".cls2{...}" 的匹配效率比 ".cls1 .cls2{...}" 要高
避免使用"border:0" -- "border:0"其实只是定义了边框的宽度为0,但边框样式、颜色等还是会被浏览器解析, 从而造成不必要的性能损失. 特别是"* {border:0;}", 这将对解析性能带来很可观的损耗. 推荐使用 "border:none;"
避免使用css表达式 -- css有它的特殊性, 它在页面加载及之后的很多行为中都会被重复解析. 它是整个页面中最繁忙的模块, 因此应尽量避免在其上使用如表达式这种低效率计算. 如果有需要, 使用js去实现.
将样式表放在 head 中 -- 浏览器为了避免样式变化所产生的多次重绘, 会在所有样式表加载完成后才进行页面渲染; 因此尽量提前样式表的加载时机, 可提高页面的渲染速度
合并和压缩css
这里以yuicompressor为例, 结合ant实现css的静态合并和压缩
<?xml version="1.0"?> <project default="minify_css" basedir="."> <property name="source.path" value="."/> <property name="target.path" value="."/> <property name="lib.path" value="."/> <target name="minify_css"> <echo message="start merge css"/> <concat destfile="${target.path}/compress.css" force="true"> <filelist files="${source.path}/a.css, ${source.path}/b.css" /> </concat> <echo message="start compress css"/> <apply executable="java" dest="${target.path}" failonerror="true" append="false" force="true"> <fileset dir="${target.path}" includes="compress.css"/> <arg line="-jar ${lib.path}/yuicompressor.jar --charset utf-8 --type css -o" /> <srcfile/> <targetfile/> <mapper type="glob" from="*.css" to="*.css" /> </apply> <echo message="finish css minimize"/> </target> </project>
"-o" -- 这里表示以文件输入, 否则结果将只输出到控制台
srcfile & targetfile -- 这里表示把fileset里的所有文件映射到srcfile, 经过压缩后, 按mapper指定的规则加上dest指定的路径将得到的结果映射到targetfile, 从而达到多个文件逐一压缩的目的.
浙公网安备 33010602011771号