在一个典型的用例中,冗余的Sass选择器会导致性能下降吗



这是一个我觉得已经知道答案的问题,但我要求再次确认。

在Sass中使用嵌套会导致一些多余的选择器,但我相信压缩不会造成问题。

考虑以下Sass输出:

.ease-of-use .ex-snippet-icon-left-with-accordion .exact-container.container.ex-container-fixed .accordion .items .toggle-content .promo .text p:first-of-type .ex-icon-plus {
margin-top: 15px;
}
.ease-of-use .ex-snippet-icon-left-with-accordion .exact-container.container.ex-container-fixed .accordion .items .toggle-content .promo .text p:first-of-type .ex-icon-minus {
min-height: 50px;
}
.ease-of-use .ex-snippet-icon-left-with-accordion .exact-container.container.ex-container-fixed .accordion .items .toggle-content .promo .text p:first-of-type .ex-icon-multiply {
margin-top: 20px
}
.ease-of-use .ex-snippet-icon-left-with-accordion .exact-container.container.ex-container-fixed .accordion .items .toggle-content .promo .text p:first-of-type .ex-icon-multiply:before {
font-size: 54px
}
.ease-of-use .ex-snippet-icon-left-with-accordion .exact-container.container.ex-container-fixed .accordion .items .toggle-content .promo .text p:first-of-type .ex-icon-question img {
margin: 24px 0 12px 0
}

当你学习压缩时,这是你必须理解的第一个概念,任何多余的字符串都会被一个较短的字符串取代,并且在解压缩时原始字符串会被交换回来。。。

如果压缩在服务器上的生产中被启用(我知道在这种情况下是这样(,那么Sass嵌套产生的冗余选择器对文件大小的影响应该可以忽略不计,对吧?

我是不是遗漏了什么?

我这么问是因为我想我被要求重构Sass,以减少Sass输出中多余的选择器。如果我是对的,那么从中可以得到的东西很少。

减压可能需要更多的时间,但似乎也应该忽略不计,除非减压量过大。

我的思考过程是对的吗?主要问题是来自服务器的压缩,即gzip。

@cs.matyi在这里的回答确实很有帮助,但它并没有回答我关于服务器上的gzip压缩的主要问题。我想知道与其他优化相比,压缩是否会使重构SASS浪费时间。

我不知道你是如何定义";可忽略";,也不是";可合理忽略";。的确,像这样重复的字符串会被gzip大大缩小大小。但并非一无所获。我压缩了你的例子,如果我删除gzip并压缩头和尾(因为对于更现实、更大的输入,它们只占总数的一小部分(,1024个字节就减少到了167个字节。第一行占用102个字节,随后的每行占用12到22个字节。

这里是压缩数据的分解;匹配x y";行表示从y字节开始复制x字节:

literal '.ease-of-use .ex-snippet-icon-left-with-accordion
match 4 37
literal 'act-
match 3 31
literal 'tainer.
match 10 10
match 3 63
match 9 13
literal '-fixed .
match 11 57
literal 'items .toggle
match 5 42
literal 'ent .promo
match 3 23
literal 'ext p:first
match 4 145
literal 'typ
match 6 146
match 5 138
literal 'plus {
literal 10 ' 
match 3 1
literal 'margin-top: 15px;
literal 10 '}
literal 10 10 '.
match 167 200
literal 'min
match 10 201
match 3 198
literal 'height: 50
match 176 201
literal 'ultiply
match 19 405
literal '2
match 3 204
match 180 203
literal ':before
match 7 210
literal 'f
match 3 68
literal '-size
match 3 413
literal '4
match 174 209
literal 'quest
match 4 70
literal 'img
match 13 416
match 3 412
match 3 203
literal ' 0 12
match 4 7
match 3 212

基于您提供的共享代码片段,如果有很多冗余的css选择器,它可能会影响性能。当然,当你的编译器压缩这些代码时,你会在生成的文件大小上赢得很多,浏览器会更快地加载所提供的css。

在我看来,深度嵌套的类将很难长期保持
根据Sass文档,如果你必须嵌套超过3级的类,你应该考虑重新思考你的html/css结构。

嵌套规则非常有用,但它们也会使您难以可视化实际生成的CSS数量。嵌套得越深,为CSS提供服务所需的带宽就越多,浏览器渲染CSS所需的工作也就越多!

希望它能回答你的问题。

最新更新