一些优化建议

  • 权重问题敷衍塞责、滥用。!important 泛滥,id 滥用以提高权重,内联样式滥用。
  • 尽可能少用大规模遍历的 Selector:注意从 右到左 的选择器原则,尽可能用最少次数的Selector来实现元素修改。
  1. <!-- 在css 中严格禁止使用此语法 -->
  2. /* “*” 导致CSS渲染引擎在渲染CSS的时候,使用*遍历整个DOM 树,影响性能渲染性能 */
  3. * { padding: 0; margin: 0; border: 0; }
  • 杜绝长串的 CSS 选择器:理解性差、可读性差、性能差,高权重,自上而下的粗放式命名
  • 杜绝冗余和重复的选择器:能够合并的请尽量合并到一条,能够共享的,请尽量共享属性
  • 精简CSS单位,利用推荐的单位执行:em
  • 去掉没有生效的 CSS 代码:高度冗余的代码
  • 集中 Hack.css 代码:方便后期管理和考察
  • 重视文档注释和文档质量
  • Minify Code
  • 使用 LESS/SASS 等预处理器,处理大型项目

will-change 优化

/* Keyword values */
will-change: auto;
will-change: scroll-position;
will-change: contents;
will-change: transform;        /* Example of <custom-ident> */
will-change: opacity;          /* Example of <custom-ident> */
will-change: left, top;        /* Example of two <animateable-feature> */

/* Global values */
will-change: inherit;
will-change: initial;
will-change: unset;
  • 除非遇到性能瓶颈,我们才使用,要知道这个属性的使用往往会付出沉重的代价。
  • 只有很少一部分元素才能够使用这个元素。
  • 推荐「动态调用」Demo 如下:
// Set will-change when the element is hovered
el.addEventListener('mouseenter', hintBrowser);
function hintBrowser() {
  // The optimizable properties that are going to change
  // in the animation's keyframes block
  this.style.willChange = 'transform, opacity';
}

Ref: