How to use CSS to improve page performance?

Continue to create, accelerate growth! This is the 4th day of my participation in the "Nuggets Daily New Plan · October Update Challenge", click to view the details of the event

Hi, my name is CoderBin

I. Introduction

Every web page is inseparable css, but many people think that it cssis mainly used to complete the page layout, such as some details or optimization, so there is no need to think about it. In fact, this kind of thinking is incorrect

As an important part of page rendering and content display, it cssaffects the user's first experience of the entire website

Therefore, in the entire product development process, cssperformance optimization also needs to run through the whole process

2. Implementation method

There are many ways to implement, the main ones are as follows:

  • Inline above-the-fold critical CSS
  • Load CSS asynchronously
  • resource compression
  • Use selectors wisely
  • Reduce the use of expensive properties
  • don't use @import

2.1 Inline key CSS above the fold

When opening a page, the time when the main content of the page appears on the screen affects the user's experience, and by inlining the csskey code, the browser can render it immediately htmlafter . If the external reference code is encountered cssin the process of parsing the structure, the external file will be downloaded and then rendered. So, inline use makes rendering time advancehtmlcsscssCSS

Note: But larger csscode is not suitable for inlining (initial congestion window, no cache), while the rest of the code is externally referenced

2.2 Load CSS asynchronously

Rendering is blocked until the CSSfile request, download, and parsing are complete, CSSand the browser will not render any processed content. After the inline code is loaded in the front, cssthere is no need to block the browser rendering after the external reference. At this time, the asynchronous loading scheme can be adopted, mainly as follows:

  • Insert the link tag at the end of the head tag using javascript

    // 创建link标签
    const myCSS = document.createElement( "link" );
    myCSS.rel = "stylesheet";
    myCSS.href = "mystyles.css";
    // 插入到header的最后位置
    document.head.insertBefore( myCSS, document.head.childNodes[ document.head.childNodes.length - 1 ].nextSibling );
    复制代码
  • 设置link标签media属性为noexis,浏览器会认为当前样式表不适用当前类型,会在不阻塞页面渲染的情况下再进行下载。加载完成后,将media的值设为screenall,从而让浏览器开始解析CSS

    <link rel="stylesheet" href="mystyles.css" media="noexist" onload="this.media='all'">
    复制代码
  • 通过rel属性将link元素标记为alternate可选样式表,也能实现浏览器异步加载。同样别忘了加载完成之后,将rel设回stylesheet

    <link rel="alternate stylesheet" href="mystyles.css" onload="this.rel='stylesheet'">
    复制代码

2.3 资源压缩

利用webpackgulp/gruntrollup等模块化工具,将css代码进行压缩,使文件变小,大大降低了浏览器的加载时间

2.4 合理使用选择器

css匹配的规则是从右往左开始匹配,例如#markdown .content h3匹配规则如下:

  • 先找到h3标签元素
  • 然后去除祖先不是.content的元素
  • 最后去除祖先不是#markdown的元素

如果嵌套的层级更多,页面中的元素更多,那么匹配所要花费的时间代价自然更高

所以我们在编写选择器的时候,可以遵循以下规则:

  • 不要嵌套使用过多复杂选择器,最好不要三层以上
  • 使用id选择器就没必要再进行嵌套
  • 通配符和属性选择器效率最低,避免使用

2.5 减少使用昂贵的属性

在页面发生重绘的时候,昂贵属性如box-shadow/border-radius/filter/透明度/:nth-child等,会降低浏览器的渲染性能

2.6 不要使用@import

css样式文件有两种引入方式,一种是link元素,另一种是@import

@import会影响浏览器的并行下载,使得页面在加载时增加额外的延迟,增添了额外的往返耗时

而且多个@import可能会导致下载顺序紊乱

比如一个css文件index.css包含了以下内容:@import url("reset.css")

那么浏览器就必须先把index.css下载、解析和执行后,才下载、解析和执行第二个文件reset.css

2.7 Others

  • Reduce reflow operations, and reduce unnecessary repaints
  • Know which properties can be inherited and avoid rewriting them
  • cssSprite, synthesizes all icon images, shows the icon image we want with the background image of width and height plus background-position, reducing http requests
  • Convert small icon images to base64 encoding
  • CSS3 animation or transition try to use transform and opacity to achieve animation, do not use left and top properties

3. Summary

cssThe way to achieve performance can be considered from the three aspects of selector nesting, attribute characteristics, and reduction http, and also pay attention cssto the loading order of the code


Every sentence: A wise person is not necessarily inherently smart, but more through life-long efforts. Now, among those of us who are studying, many of them think that they are inherently insufficient and cannot learn well, so they are pessimistic and discouraged and unwilling to learn. In fact, this is not necessary, as long as you work hard, hope is in front of you.

This is the end of this sharing. If the content of this chapter is helpful to you, please like + favorite . If there is something wrong with the article, please point out, and if you have any questions, you can leave a message in the comment area. I hope everyone can gain something, let's discuss and make progress together!

Guess you like

Origin juejin.im/post/7150448371059130404