CSS performance optimization

Posted by suomynonA on Wed, 12 Jan 2022 12:23:50 +0100

What are the ways to improve performance?

1. merge css File, if 10 pages are loaded css file,1 per file k,Then it's better than loading only one 100 k of css File slow.
2. reduce css Nesting, it is best not to nest more than three layers.
3. Don't be ID Nested in front of the selector, ID It is unique and has a large permission value. Nesting is a waste of performance.
4. Create a public style class and extract the same style for use as a public class.
5. Reduce wildcards*Or something like that[hidden="true"]This kind of selector is used to find all the data one by one...Does this work well?
6. Ingenious use css If the parent node is defined, the child node does not need to be defined.
7. Split public css File. For larger projects, you can extract the public structure styles of most pages and put them separately css In the file, after such a download, it will be put into the cache. Of course, this method will increase requests. The specific method should depend on the actual situation.
8. no need css Expressions, expressions just make your code look cool, but the waste of performance may be more than you think.
9. Use less css rest,You may think that resetting the style is standard, but in fact, many operations are unnecessary and unfriendly. You can choose if you are interested in it normolize.css. 
10. cssSprite,Synthetic all icon Picture, with width and height plus background-position Display in the form of background map icon Figure, this is very practical and reduces http Request.
11. Rehabilitation work, css compress(Online compression tool YUI Compressor)
12. GZIP Compression is a popular file compression algorithm.

performance optimization

> 1. Avoid using @ import. Using @ import in an external css file will add extra delay to the page loading.

First, using @ import to introduce css will affect the parallel download of browsers. For the css file referenced by @ import, only after the css file referenced by @ import is downloaded and parsed, the browser will know that another css needs to be downloaded. At this time, it will download it, then start parsing after downloading, build render tree and other operations, which makes the browser unable to download in parallel
The desired style file.
Secondly, multiple @ imports will cause the download order to be disordered. In IE, @ import will cause the download order of resource files to be disrupted, that is, the js files arranged behind @ import take precedence over @ import download, and disrupt or even destroy the parallel download of @ import itself.
So don't use this method, just use the link tag.

> 2. Avoid excessive rearrangement

  • In order to re render part or the whole page, the browser recalculates the position and geometry of page elements, which is called reflow
  • The browser calculates according to the defined style and puts the element where it should appear. This process is called reflow
  • Any node on the page triggers reflow, which will cause its child nodes and ancestor nodes to re render
  • What causes reflow to occur
 1. Change the size of the window  
 2. Change text size
 3. Add or remove style sheets
 4. The content of the change input box will also change
 5. Activation of pseudo classes
 6. operation class attribute
 7. Script operation dom js change css class
 8. calculation offsetWidth and offsetHeight
 9. set up style attribute
 10.Change the inner and outer margins of elements 
  • Common rearrangement elements
 1. Size dependent width,height,padding,margin,border-width,border,min-height
 2. Layout related display,top,position,float,left,right,bottom
 3. Font related font-size,text-align,font-weight,font-family,line-height,white-space,vertical-align
 4. Hide related overflow,overflow-x,overflow-y
  • Suggestions for reducing reflow's impact on Performance
 1. Don't modify one by one dom Predefined style class,Then modify dom of classname
 2. Do not modify the with large influence range dom
 3. Use absolute positioning for animated elements
 4. No table Layout, because a small change will cause the whole table Rearrange
 5. Avoid setting a large number of style Properties by setting style Property to change the node style, each setting will trigger once reflow,So it's best to use class attribute
 6. If css There is a calculation expression in it. It will be recalculated and triggered once every time reflow

> repaint

  1. When the appearance of an element is changed, but the layout is not changed
  2. When the element changes, it does not affect the position of the element in the page. The browser will only redraw the element with a new style
  3. Common redraw elements
 - colour color,background
 - Border style border-style,outline-color,outline,outline-style,border-radius,box-shadow,outline-width
 - Background related background,backgound-image,background-position,background-repeat,background-size

>CSS animation

  1. CSS animation enables GPU acceleration, and the graphics performance of GPU is applied to hand over some graphics operations in the browser to GPU. Canvas 2D, layout synthesis, css3 conversion, css3d conversion, webGL, video
  2. 2d acceleration
  3. 3d acceleration

>File compression

The easiest and most common method for performance optimization is file compression, which is often effective
The size of the file will directly affect the loading speed of the browser, especially when the network is poor. The construction tools webpack, gulp/grunt and rollup can be significantly reduced after compression, which can greatly reduce the loading time of the browser.

>Remove useless CSS

Although file compression can reduce the file size, css file compression usually only removes useless spaces, which limits the compression ratio of css files. If the compressed file still exceeds the expected size, you can try to find and delete useless css in the code.
In general, there are two kinds of useless CSS code:

  1. Duplicate codes for different elements or other situations,
  2. There is no effective CSS code in the whole page

>Use selectors selectively

cssselector The matching is from right to left, which leads to the performance difference between different kinds of selectors. Compared with #markdown-content-h3, it is obvious to use #markdown Content H3, the browser takes more time to generate the rendering tree. Because the latter needs to find all H3 elements in the DOM first, and then filter out the ancestor elements Content, and finally filtered out Content is not #markdown. Imagine that if there are more elements in the page, the time cost of matching is naturally higher.
It seems that browsers have made a lot of optimizations in this regard. The performance difference of different selectors is not obvious, or even very small. In addition, the performance of different selectors in different browsers is not uniform. When writing css, it is impossible to take into account each browser. In view of these two points, try to remember the following points when using selectors:

 1. Keep it simple and don't use too many nested and complex selectors
 2. Wildcards and attribute selectors are the least efficient and need to match the most elements. Try to avoid them.
 3. Do not use class selectors and ID Selectors decorate element labels, such as: h3#Markdown content, which will reduce efficiency
 4. Don't give up readability and maintainability in pursuit of speed

TIPS: why do css selectors match from right to left?
More selectors in css will not match, so when considering performance issues, we need to consider how to improve efficiency when selectors do not match. Matching from right to left is to achieve this purpose. This strategy can make css selectors more efficient when selectors do not match.

>Reduce the use of expensive attributes

When the browser draws the screen, all the attributes that need to be operated or calculated by the browser need to cost more. When the page is redrawn, they will reduce the rendering performance of the browser. Therefore, when writing css, you should minimize the use of expensive attributes, such as:
Box shadow, border radius, filter, transparency,: nth child, etc
Of course, it's not that you don't use these attributes. These attributes are often used, but they can be used as an understanding here. When there are other schemes to choose, you can give priority to the scheme with no or less expensive attributes, and the performance of this website will be improved unconsciously.

>Hardware acceleration is good or bad

  1. It's not enough to rely on GPU alone. Many animations still need the intervention of CPU. The total bandwidth connecting CPU and GPU is not unlimited, so we need to pay attention to the transmission of data between CPU and GPU, try to avoid channel congestion, and always pay attention to the transmission of pixels.
  2. One key point is to understand the number of composite layers created. Each layer corresponds to a GPU texture. Too many layers will consume a lot of memory.
  3. ** chrome://flags/#composited -Layer borders * * address of observation.
  4. The composite layer of each dom element is marked with an additional border, which can verify whether there are many layers
  5. Another key point is to keep the transmission volume between GPU and CPU to a minimum, that is, the number of layer updates should be an ideal constant. Each time the layer is updated, a pile of new pixels may need to be transmitted to GPU.
  6. For high performance, it is also very important to avoid layer updating after the animation starts, so as to avoid congestion caused by constant updating of other layers during the animation.
  7. That is to use these css attributes to realize Animation: transformation, opacity, filter
  8. Use performance tools to check the rationality of optimization, and timeline to check whether optimization is reasonable. It also needs to realize automatic operation to do performance regression test.
  9. It is very useful to detect the number of layers and the number of layer updates.

Reprint: *** Twelve blogs - CSDN blog_ css performance optimization

Topics: Front-end css Optimize