Recently, I want to systematically learn the knowledge of front-end performance optimization. I have checked a lot of information and combed it with my actual experience

Content of this article:

  1. Browser rendering process
  2. How to optimize the rendering process?

CRP Critical Render Path

This is the key concept of performance optimization in this chapter, and I will elaborate on each step of optimization around the mechanics and steps of rendering, in turn improving the rendering speed and performance of the page.

1. Request data back from the server based on HTTP network:

The CSS request also follows this process

  • A hexadecimal file stream
  • The browser parses the data into HTML strings
  • Identified as a node according to W3C rules
  • Generate a DOM tree

2. Visit the page, the request is returned HTML document, browser rendering from top to bottom, the server will open up multiple threads to execute

  • GUI rendering thread: Render pages
  • JS engine threads: Render Javascript code
  • HTTP threads: Multiple threads can be created to pull resource data from the server
  • DOM listening thread

3. Page rendering process

CSS

  1. When you encounter an inline Style, render directly

    • So whenCSSThe code is lessWhen, yesUse inline styles directly, because the HTML is pulled, the CSS is pulled and rendered at the same time
    • However, when the code is large, it may affect the speed of HTML pulling, and is not conducive to code maintenance, so it is better to use the external chain
  2. With link’s outgoing style, the browser creates an HTTP thread to asynchronously request resource file information, and the GUI thread continues rendering

    • However, HTTP threads are limited. For example, if the number of concurrent HTTP requests exceeds the maximum number of concurrent HTTP requests (5-7), it will need to queue (the fewer HTTP requests must be the better).
  3. When @import is encountered, the browser also opens an HTTP thread to request resource file information, but the GUI thread is blocked and must wait for the resource request to complete before continuing rendering

    • Be sure to avoid @improt in real projects

A link is usually placed in the header of the page so that while rendering the DOM, the HTTP thread goes to the server and pulls the CSS. When the DOM is rendered, the CSS is pulled. This allows for more efficient use of time and faster page rendering through concurrent processing.

JavaScript code handling:

You should either place the JavaScript code at the bottom of the page to prevent it from blocking the GUI rendering thread, or give the script tag defer or Async

  1. GUI rendering is blocked when a <script> tag is encountered

    ifasyncattribute

    • The browser will request the JS resource and the GUI will continue rendering, but as soon as the resource request is complete, the GUI will block and load the JS code

    encounterdeferattribute

    • The browser requests the JS resource, the GUI continues rendering, waits until the entire DOM structure is loaded, and then comes back to load the JS code

Summary: browser rendering flow

After the DOM is loaded, it is possible to load JavaScript code, assuming the CSS has not yet been requested

  1. Process HTML tags and build DOM trees

  2. Process CSS tags and build CSSOM trees

  3. Combine the DOM tree and CSSOM tree into the RENDER tree

  4. According to the generated render tree, calculate the size of their exact position in the viewport. This calculation stage is called Layout.

  5. According to the geometry information of rendering tree and backflow, the absolute pixels of nodes are obtained and the page is painted.

We can see that in stage 4 if you change the layout, you have to go down to stage 5, and that’s why redrawing always triggers redrawing, but redrawing doesn’t necessarily trigger redrawing. Right

The drawing stage is layered drawing, we can see the benefits of layered drawing through jingdong.

1. Chorme F12 => click on the right to hand over three dots => More Tool => Layer

As you can see from the figure above, these levels are actually what we call out-of-document flow. The advantage of this is that we operate on these out-of-document DOM elements, which causes the hierarchy it belongs to to backflow.

Optimization scheme

  1. Avoid deep nesting of tags and semantic tags as much as possible
  2. Pull the CSS code to the client as quickly as possible
  3. Avoid JavaScript code blocking rendering
  4. Reduce backflow and redraw

What operation causes Reflow:

  1. Page first render

  2. The size and position of DOM elements change

  3. Change the content of the element (change the text, add a different size image)

  4. Add the name of the class

  5. Manipulating the DOM(adding or removing visible DOM)

  6. Get attributes such as the viewport position of the DOM element (clientWidth, clientHeight, clientTop, clientLeft offsetWidth)

Summary: It is clear that operations that affect the size and structure of DOM elements, as well as operations that retrieve information about the size of DOM elements, will be backflowed.


For the fourth point, we have an optimization idea, which is: “minimize browser backflow.”

We can do it

Point 1: Render the page for the first time (this can’t be done)

Point 2: As much as possible, we want all such operations to be done in one reflux

Point 3 and 4:

  • Style changes should also be made as centrally as possible:
[DOM].style.cssText = "width:300px; height:200px; border:1px solid red;"

.box {
  width:300px;
  height:200px;
  border:1px solid red;
}
[DOM].style.className = 'box'
Copy the code

Point 5:

  • Abandon the era of traditional DOM manipulation and influence views through data based on Vue/React
  • Bulk modification of elements (document fragmentation)
let box = document.querySelector('#box')
let frag = document.createDocumentFragment()
for(leti = 0; i < 10; i++){
	let span = document.createElement('span')
    frag.append(span)
}
box.append(frag)
Copy the code

Point 6:

  • Cache the style information we get
let boxWidth = box.offsetLeft // Save it to avoid retrieving it every time you use it
Copy the code

Other:

  1. Animated DOM elements that are out of absolute/fiex document flow

  2. CSS Hardware Acceleration (GPU)

    • transform/filter/opacity: Use these attributes to detach elements from a separate layer and perform hardware acceleration, such astransfromDo animation, it’s better than usingleftAnd other properties have better performance, both hardware acceleration without causing backflow
    • Or add one to the elementtransform: translateX(0)It’s also possible to trick the browser into hardware acceleration for an element, but obviously abusing memory like this is not a good idea.
  3. Avoid table layouts and JavaScript expressions with CSS

Browser automatic optimization policy

It is often very energy-intensive for browsers to do backflow for every line of code executed, so it is common to put all operations into a queue and render centrally

Render queue Refresh render queue conditions:

  1. No modified style code
  2. Get element style code encountered

In both cases, the render queue immediately triggers the backflow mechanism.

The code level

Webpack level optimization

Use my previous project to optimize ~

  1. Introduced the CDN
// vue.config.js
  configureWebpack: {
    externals: {
      vue: 'Vue'.'vue-router': 'VueRouter',}}// index.html
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    <script src="/ / cdn.bootcss.com/vue-router/2.5.3/vue-router.min.js"></script>
Copy the code
  1. Route lazy loading
const categoryEdit = () = > import('@/views/CategoryEdit')

 path: '/categories/create'.component: categoryEdit
Copy the code

Before optimization:

After the optimization:

I used CDN to introduce several of the biggest modules, and I have to say the effect is really shocking..



Thank 😘


If you find the content helpful:

  • ❤️ welcome to focus on praise oh! I will do my best to produce high-quality articles

Contact author: Linkcyd 😁 Previous:

  • Scope and closures: The worst interview question, did you get it right?
  • Prototype and Prototype Chain: How to implement Call, Bind, New yourself?
  • Data type testing: That’s all the interviewer can ask