Render Impact List of CSS properties >>


The performance is introduced


The Performance panel of Chrome DevTools records and analyzes all the activity of the page at run time.

With the traceless mode, you can avoid the impact of chrome plugins.

Frame rate figure

1. Record and view

  • 1312.3 ms: Time of one frame
  • 1fps: Frames per second

The following section is a snapshot of the web page, which the browser takes at regular intervals.

2. View it in real time

The shortcut CTRL + Shift + P allows you to view the frame rate in real time

  • Flashing highlights the parts of the web page that need to be repainted.
  • Layer Borders Displays Layer boundaries.
  • FPS Meter frame details per second, frame rate distribution information and GPU memory usage.
  • Scrolling Performance Issues are analyzed. The areas that slow Scrolling are displayed.
  • Emulate CSS Media. This allows you to view CSS styles on different devices. The options include print and Screen

Flame figure

  • Loading: Network communication and HTML parsing
  • Scripting: Javascript execution
  • Rendering: Style calculation and layout, rearrangement
  • Painting: Repainting the corresponding detailed events >>>

How do I see performance problems?

1. The Red Triangle

  • Handler took XXX MS Too much time
  • Forced reflow is likely performance bottleneck, which can cause performance problems, usually because the browser has to re-render to get the latest property values.

2. Layout jitter

3. The long frame

Animation should be played at 60 frames per second, or 16.6ms per frame.


The instance


1. Parsing HTML (excluding JS CSS external files)

  • Readystatechange (first) (document loaded and parsed) is in an interactive state, which means the document is loaded and parsed but the resource is still loaded. DomContentLoaded is usually followed by this state.
  • Trigger when the DOM tree is completed when the HTML document is successfully loaded and parsed.
  • Recalculate Style (CSSOM built) Changing the DOM by adding and removing elements, changing properties, classes, or animating all cause the browser to Recalculate the element Style and, in many cases, layout the page or part of the page (that is, automatically rearrange it). Recalculating the style can be done in two steps:
  1. The browser calculates which classes, pseudo-selectors, and ids to apply to the specified element.
  2. Gets all the style rules from the match selector and calculates the final style for this element.
  • Readystatechange (second) (the document is loaded and parsed, and the resource is loaded) has a complete state, indicating that both the document and the resource are loaded, which is usually followed by load.
  • The load event is emitted when both the document and the resource have been loaded. More page load completion events >>.
  • Layout is almost always applied to the entire document, but it depends on the number of nodes affected.

2. Parsing HTML (including JS CSS external files)

  • Evaluate Script
  • Layouts may not be executed in ParseHtml because loading CSS files or JS files blocks the entire rendering process of the page, since both JS and CSS can style tags. If there were no files, there would be no problem waiting to load.

3. Change the background color (repaint)

4. Change height (rearrange)

There is one more Layout relative to redraw

5. Image resource loading (IMG or BG)

If the image label size does not change, a redraw is triggered


Principles to be followed


1. About blocking

  • CSS loading does not block DOM tree parsing; CSS parsing blocks;
  • CSS loads and parses block JS (so inline styles do not need to be loaded and are good for the first screen)
  • Js blocks parsing of the DOM tree (because JS changes the tree content)
  • CSS introduced font file loading will also block JS, page rendering

2. About withPage rendering processThe corresponding

  1. Js execution: At this point, only the DOM tree and CSSOM tree of the previous section should be built, because JS needs to manipulate the content and style of the tags of the previous section through the DOM API and CSSOM API.
  2. DOM tree construction completed: DomContentLoaded event
  3. CSSOM build complete, Render Tree build complete: Recalculate Style
  4. Layout: Layout events
  5. Paint: Paint and Composite Layers. Changing any property other than transform or opacity always triggers painting paint.
  6. Reflow rearrangement: 3, 4 and 5 steps
  7. Repaint: 3 5 steps once
  8. Change a property that neither layouts nor draws: 3 steps + Composite Layers, which is the least expensive of the 678 re-rendering steps and is suitable for animating or scrolling, such as transfrom opacity.

3. Some behavior about Chrom

  • Render queue: The browser has a render queue that is used to turn multiple consecutive rearrangements and redraws into one. When you do a DOM read and the queue is not empty, Chrome empties the queue and rearranges or redraws it immediately. If it is empty, Chrome does nothing superfluous.
  • Layout: In layout or rearrangement, the browser calculates how much space elements take up and where they fit on the screen. The layout pattern of a web page means that one element can affect other elements, for example<body>The width of an element generally affects the width of its child elements as well as nodes throughout the tree.
  • Drawing and Composition: Drawing is generally done on multiple surfaces (often called layers), so the browser needs to draw them onto the screen in the right order to render the page correctly.
  • CSS selector: for complex CSS selectors, browsers need to spend more time to determine the style of the elements, so class-centric CSS writing principles, such as: NTH-last-child pseudo-class can be replaced by a separate class (~ ▽ ~).

Performance optimization


Blocking the optimization

  • Js has problems: 1) DOM parsing and page rendering will be blocked when JS loading and executing; 2) If third-party scripts are referenced, the page will be blank when third-party service providers request delay; Js workaround: Pages can load JS asynchronously by adding the keywords defer and async.

  1. Async (see Ajax) : Asynchronous loading does not block DOM parsing and page rendering; The execution time is when the load is complete. Block when executed, but the DOM may have been parsed or even rendered; In addition, the order of js file execution will be affected. Defer: Asynchronous loading does not block DOM parsing and page rendering; The execution time is after the DOM parsing is complete and before the DOMContentLoaded event (thus blocking the DCLoad event and jquery’s Ready event). The DOM is already parsed at execution time and only blocks page rendering.
  2. Js file loading order Synchronous > Asynchronous same as async In the order of loading completion same as defer In the order of introduction Async defer Normal Use different

Reduce rerendering

About CSS

  • Use simple style sheets. The simpler the stylesheet, the faster the rearrangement and redrawing. Specific as follows:
  1. Reduce the complexity of the selector and reduce the use of pseudo classes; Use class-centric methods, such as BEM;
  2. Reduce the number of elements whose styles must be computed, and the number of elements declared invalid should be minimized.
  • Reduce the DOM element hierarchy. The higher the level of DOM elements rearranged and redrawn, the higher the cost.
  • Use display: None. The display: None element is not rendering the tree and therefore will not be rearranged or redrawn
  • Use CSS animations instead of JS animations. CSS animation is superior to JS animation because CSS changes the translate value and does not change the offsetLeft, offsetTop, and other positions.
  • Use Absolute instead of float. Elements with position attributes such as absolute or fixed have less rearrangement overhead than float, because you don’t have to worry about its effect on other elements.
  • Use divs instead of tables. Because even a small change can cause the entire table to be rearranged, such as a TD content change.

About the JS

  • Multiple DOM reads (or writes) should be placed together, not interspersed. Because the element styles are set consecutively (writes), the browser does them all at once, triggering only one rearrangement or redraw, but if a read style is inserted between several writes, the browser has to rearrange or redraw them immediately.
  • Change styles once. Don’t change styles one by one, but by changing the class, or the el.style.csstext property.
  • Use the offline DOM to change element styles. Such ascloneNode()Clone the node and then replace the element node orDisplay: None → Change → display.
  • Modify the DOM as low as possible.
  • Do not read DOM node property values repeatedly in a loop.
  • Use Windows. RequestAnimationFrame (), window. RequestIdleCallback () these two methods to control rendering.

Improved FPS (Frame per second)

Each frame of a web animation is re-rendered, and the order in which each frame is sent to the screen is as follows:

  • < 24 frames: The pause can be felt by the human eye
  • 30-60 frames: Relatively smooth
  • Considering that the refresh frequency of most monitors is 60Hz, that is, 60 times per second, if the FPS is higher than 60, the output will be higher than 60 pictures per second, then ifFPS > Refresh frequencyThe multi-output screen will have invalid frames, no improvement in fluency, but no harm either (manual funny d :).

The point here is that an FPS is best suited to a browser refresh rate, so be careful not to perform too many performance consuming operations when playing animations.

Manual control of re-rendering

Some code window. RequestAnimationFrame () method can be unified into the next time to render. The js code is executed at the start of the next frame. If you use setTimeout or setInterval to perform visual changes like animation, the callback might be executed at some point in the frame, maybe at the end, and that would cause us to lose the frame and get stuck.

  1. Handling “Layout jitter” Repeated read and write properties cause layout jitter, resulting in long frames.
function doubleHeight(element) {
    var currentHeight = element.clientWidth;
    element.style.width = (currentHeight / 2) + 'px';
    element.style.height = '80px';
}
var elements = document.getElementsByTagName('tr');
for (var i = 0; i < elements.length; i++) {
    doubleHeight(elements[i]);
}
Copy the code

function doubleHeight(element) {
    var currentHeight = element.clientHeight;
    window.requestAnimationFrame(function () {
      element.style.height = (currentHeight * 2) + 'px';
    });
}
Copy the code

2) Page scroll event

$(window).on('scroll'.function() {
   window.requestAnimationFrame(scrollHandler);
});
Copy the code

3) Best for animation

Combined with the project

Now in projects, pages (for example, “task” pages) request Ajax data when they load, such as datagrid, tree data, etc., and some Ajax data is just preloaded. If these Ajax requests complete before the page renders, they block the page rendering. So there are two rendering sequences for the same page at different network speeds:

  • Execute after rendering

  • Executed before rendering

The solution

  1. Ajax requests are made after all resources are loaded. Puts the data load of controls such as the Datagrid in the $(window).load() event.
  2. Lazy initialization of the content in Modal

The effect


The problem


Q: What is the order of request and execution when requesting a JS file?

A: Requests are sent together; The order of execution is the order of introduction, not because the last one returns data first.

Q: Does ajax request some data before the page loads affect performance?

A: Maybe, maybe not. Performance is not affected when ajax requests are made, but when callback functions are executed after the request. The Ajax callback function is executed after the request is completed and the JS main program runs. When we can see the page, we need to go through the two processes of page parsing and rendering. If the Ajax callback is executed before the page rendering, it will block the rendering process.

Q: Why does jquery usually execute code in the ready method?

A: Ready monitors the DOMContentLoaded event, which monitors that the DOM tree has been built.

The appendix


Loading events

The event describe
Parse HTML The browser performs HTML file parsing
Parse Stylesheet Browser performs CSS file parsing (external CSS files only)
Finish Loading Network request completion event
Receive Data The response data of the request arrives at the event, which may be triggered multiple times if the response data is large (unpacked)
Receive Response Triggered when the response header packet arrives
Send Request Triggered when a network request is sent

Scripting event

The event describe
Animation Frame Fired Triggered when a defined animation frame occurs and the callback processing begins
Cancel Animation Frame Triggered when canceling an animation frame
GC Event Triggered when garbage is collected
DOMContentLoaded Triggered when the DOM content in the page has been loaded and parsed
Evaluate Script A script was evaluated.
Event Js event
Function Call Triggered only when the browser enters the JS engine
Install Timer Triggered when a timer is created (calling setTimeout() and setInterval())
Request Animation Frame A requestAnimationFrame() call scheduled a new frame
Remove Timer Triggered when a timer is cleared
Time Triggered by a call to console.time()
Time End Triggered by a call to console.timeend ()
Timer Fired The timer is triggered after the callback is activated
XHR Ready State Change Triggered when an asynchronous request becomes ready
XHR Load Triggered when an asynchronous request has finished loading

Rendering events

The event describe
Invalidate layout Triggered when a DOM change invalidates the page layout
Layout Triggered when page layout calculations are executed
Recalculate style Triggered when Chrome recalculates element styles
Scroll Triggered when the embedded window scrolls

Painting event

The event describe
Composite Layers Chrome’s rendering engine is triggered when the image layer is merged
Image Decode Trigger when an image resource completes decoding
Image Resize Trigger when an image is resized
Paint Triggered when the merged layer is drawn to the corresponding display area