gpt4 book ai didi

CSS 性能 - 分组还是不分组?

转载 作者:行者123 更新时间:2023-11-28 11:26:07 25 4
gpt4 key购买 nike

我想知道 CSS 中的分组规则对解析和渲染性能有何影响。

方法一:

.class1 {
margin: 10px;
padding: 20px;
color: #ccc;
}
.class2 {
margin: 10px;
padding: 30px;
color: #ddd;
}
.class3 {
margin: 20px;
padding: 30px;
color: #eee;
}
.class4 {
margin: 20px;
padding: 20px;
color: #fff;
}

与方法 2:

.class1,
.class2 {
margin: 10px;
}
.class3,
.class4 {
margin: 20px;
}
.class1,
.class4 {
padding: 20px;
}
.class2,
.class3 {
padding: 30px;
}
.class1 {
color: #ccc;
}
.class2 {
color: #ddd;
}
.class3 {
color: #eee;
}
.class4 {
color: #fff;
}

当然,我们讨论的是具有相同规则分组的大型 css 文件,因此有时相同的选择器会被分割成很多 block 。

它对 css 解析和渲染的影响是否足够大以至于放弃这种方法以支持更大的文件,但更干净并将所有规则收集在一个选择器中?

选择器匹配可能很昂贵。在现实生活中,每个选择器不只是一个类,而是 2-3 个嵌套类。因此,对于每个元素,浏览器必须匹配选择器 3 次才能应用所有规则。首先用于边距,然后用于填充,然后应用颜色。第二种方法似乎非常昂贵。

最佳答案

我准备了两个带有两个选项的代码笔:

方法 1(每个类一个选择器)- https://codepen.io/kali187/pen/EvpVdb- (只输出:https://codepen.io/kali187/live/EvpVdb)

@for $n from 1 through 2000 {
.div-#{$n} {
float: left;
background: rgb( $n, $n, $n );
height: 10px + 1px * $n / 2;
width: 20px + 1px * $n / 5;
margin: 0 1px 1px 0;
border: 1px solid #f00;
}
}

方法 2(一个类的多个选择器)- https://codepen.io/kali187/pen/dzjGPa- (只输出:https://codepen.io/kali187/live/dzjGPa)

$max: 1000;

@for $i from 1 through $max {
%bg-#{$i} {
background: rgb( $i, $i, $i );
}
%width-#{$i} {
width: 20px + 1px * ceil($i / 5);
}
%height-#{$i} {
height: 20px + 1px * ceil($i / 3);
}
}

@for $n from 1 through (2*$max) {
.div-#{$n} {
float: left;
@extend %bg-#{ceil($n/2)};
@extend %width-#{ceil($n/3)};
@extend %height-#{ceil($n/4)};
margin: 0 1px 1px 0;
border: 1px solid #f00;
}
}

第一种方法的渲染结果: enter image description here解析样式和html ~ 25ms

第二种方法的渲染结果: enter image description here解析样式和 html ~ 75ms(3 倍长)

如果有人想测试它,请做

关于CSS 性能 - 分组还是不分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45857820/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com