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

标签 css performance parsing rendering css-parsing

我想知道 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 个嵌套类。因此,对于每个元素,浏览器必须匹配选择器三次才能应用所有规则。首先是边距,然后是填充,然后应用颜色。第二种方法似乎非常昂贵。

最佳答案

我准备了两个 codepen,有两个选项:

方法 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/

相关文章:

html - 下拉菜单按钮颜色不全,中间有奇怪的间隙

两个 div 的 CSS 属性 - 与预期的宽度不匹配

mysql - MySQL 查询速度慢 - 如何才能加快速度?

mysql - 我的 SQL 查询对于 50K+ 记录非常慢

java - PushbackReader 等效项

python - 使用 Python 解析 XML 数据

html - 自定义 Font Awesome CSS

html - Flexbox,使所有图像宽度相等以适合列表

performance - 所有资源的 HSTS header ?或文件?

parsing - 将字符串解析为 f64 和 i64