当前位置:网站首页>How to optimize performance
How to optimize performance
2022-06-24 15:20:00 【010101011001】
TL;DR: When we are doing performance optimization , What exactly are we optimizing ? Do you need to know the underlying things for performance optimization ? To what extent ? What is the underlying architecture of the browser ? What is the essence of browser rendering ? Which aspects have the greatest impact on the user experience ? Is there any general standard or benchmark reference in the industry ? all 1202 Years. , Is there any use in Yahoo's military regulations ? What are the performance analysis tools ? What is the proper way for us to analyze ?
This article answers these questions one by one . Understanding these issues , Maybe you can be more handy when doing performance optimization .
1. The essence of performance optimization
1.1 Show faster , More responsive
The purpose of performance optimization , Is to provide users with a better experience , These experiences include these aspects : Show faster 、 Fast interactive response 、 There is no jam on the page .
More on that , Is refers to , In user input url In the process of displaying the whole page completely on the site , Through various optimization strategies and methods , Make the page load faster ; In the process of user use , Make the user's operation response more timely , Better user experience .
For front end Engineers , Do a good job in performance optimization , You need to understand the nature of browser loading and rendering . Understand the essential principle , In order to better optimize . So let's take a look at the browser architecture .
1.2 Understand browser multiprocess architecture
In a big way , The browser is a multiprocess architecture .
It can be a process with multiple threads , It can also be in multiple processes , Each process has multiple threads , Between threads through IPC Communications . Each browser has different implementation details , There are no standards for how browsers must implement .
Here we only talk about chrome framework .
The following picture shows the current chrome Multi process architecture diagram of .
( The picture to quote Mariko Kosaka Of 《Inside look at modern web browser》)
Let's see which part of the browser window these processes correspond to :
( The picture to quote Mariko Kosaka Of 《Inside look at modern web browser》)
Let's see which part of the browser window these processes correspond to :
from chrome Official website and source code , We can also learn that , These processes are included in the multiprocess architecture :
● Browser process : After opening the browser , There is always one . The process has UI Threads 、Network Threads 、Storage Threads, etc . User input url after , First of all Browser The process responds and requests the server to get data . And pass it to Renderer process .
● Renderer process : every last tab One , be responsible for html、css、js The whole process of execution . Front end performance optimization is also related to this process .
● Plugin process : Related to browser plug-ins , for example flash etc. .
● GPU process : Browsers share one . Mainly responsible for Renderer Drawn in the process tile The bitmap is uploaded to as a texture GPU, And call GPU Related methods put texture draw Go to the screen .
Here is just a brief introduction to the multi process architecture of the browser , Let us have a preliminary understanding of the overall architecture of the browser , In fact, there are many details behind it , It's not going to unfold here one by one . If you are interested, you can take a closer look This series of articles and chrome Official website Introduce .
1.3 Understand the process of page rendering
1.3.1 Renderer Process & GPU Process
From the above multi Architecture , We learned that , And front end rendering 、 Performance optimization related , In fact, it's mainly Renderer The process and GPU process . that , What are their architectures ?
Take a look at this picture we are all familiar with .
( The picture to quote Paul Of 《The Anatomy of a Frame》)
● Renderer process : Include 3 Threads . Composite thread (Compositor Thread)、 The main thread (Main Thread)、Compositor Tile Worker.
● GPU process : Only GPU Threads , Responsible for receiving from Renderer In process Compositor Thread The texture passed by , Display on screen .
1.3.2 Renderer Process Detailed explanation
Renderer In progress 3 The role of threads is :
● Compositor Thread: First receive vsync The signal (vsync A signal is when the operating system instructs the browser to draw a new frame ), Any event will arrive first Compositor Threads . If the main thread does not bind Events , that Compositor Threads will avoid entering the main thread , And try to convert the input into a movement on the screen . It passes the updated layer position information as a frame GPU Thread passed to GPU Drawing .
When the user is in the process of fast sliding , If the main thread does not bind Events ,Compositor Threads can respond quickly and draw , This is an optimization done by the browser .
● Main Thread: The main thread is the thread that we front-end engineers are familiar with , Parsing will be performed here Html、 Pattern calculation 、 Layout 、 draw 、 Synthesis and other actions . So the question about performance , It all happened here . So we should focus on here .
● Compositor Tile Worker: One or more... Are generated by the composite thread worker To handle rasterization .
Service Workers and Web Workers It can be understood for the time being that Renderer In progress , There is no discussion here .
1.3.2.1 Main Thread
The main thread needs to focus on . Because this is where our code really exists .
From the previous section Render The process and GPU Process diagram , We can see a red arrow , from Recal Styles and Layout Yes requestAnimationFrame, This means that there are Forced Synchronous Layout (or Styles)( Force reflow and redraw ) happen , Pay special attention to this in terms of performance .
stay Main Thread in , There are a few things to pay attention to :
● requestAnimationFrame: Because layout and style calculation are in rAF after , So in rAF Is the ideal time to make element changes . If you change an element here 100 Classes , It's not going to happen 100 Time calculation , They will be processed in batches . It should be noted that , Can't be in rAF Query the properties of any calculation style and layout in ( for example :el.style.backgroundImage or el.style.offsetWidth), Because this will cause redrawing and reflow .
● Layout: The layout calculation is usually for the entire document , And with DOM Is proportional to the size of the element !( Pay special attention to this , If a page DOM Too many elements , It can also lead to performance problems )
The order of the main threads is always :Input Event Handler->requestAnimationFrame->ParseHtml->ReculateStyles->Layout->Update Layer Tree->Paint->Composite->commit->requestIdleCallback, Only from the front to the back , for example , Must first be ReculateStyles, then Layout、 then Paint. however , If it only needs to do the last step Paint, So that's all it has to do , It won't happen again ReculateStyles and Layout.
This actually gives us an enlightenment : If you want to make fps keep 60, That is, the number of... Per frame js Execution time is less than 16.66ms, Let the main thread execute as few processes as possible , Is our performance optimization goal .
According to these steps of the main thread , ideally , We just want the browser to take the last step :Composite( synthesis ).
CSS The attribute of is the module we need to pay attention to . What is described here CSS attribute It causes redrawing 、 Reflux and synthesis . for example , Let's move the position of an element :
transform and opacity It can directly trigger synthesis , however left and top But it will trigger Layout、Paint、Composite3 An action . So it's obvious that transform A better solution .
But that doesn't mean we shouldn't use left and top These attributes may cause redrawing reflow , Instead, you should focus on the effect of each attribute on browser performance .
2. Look at the classics : Yahoo rules
Years ago, Yahoo Nicolas C. Zakas Put forward 7 Categories 35 Rules , So far, many front-end optimization criteria have been developed around this . If you strictly follow these rules , In fact, we have a lot of optimization work to do , As long as we practice it carefully , Performance improvement is not a problem .
Let's take a look at it 7 What are the three categories all about :
● Server: Related to the page initiating the request ;
● Cookie: Related to page initiation request ;
● Mobile: Related to page requests ;
● Content: Related to page rendering ;
● Image: Related to page rendering ;
● CSS: Related to page rendering ;
● Javascript: Related to page rendering and interaction .
As can be seen from the above description , In fact, Yahoo military regulations , It is the moment when the request is made around the page , Go to page rendering completion , The page starts to interact in these aspects , Put forward some principles .
Many principles are familiar to everyone , Not all of them , Interested students can check original text . Here I would like to mention some neglected but noteworthy points :
● Reduce DOM Number of nodes
Why reduce DOM Number of nodes ?
When traversing a query 500 and 5000 individual DOM node , When binding events , It will make a difference .
When a page DOM Too many nodes , You should consider using an infinite scrolling scheme to make the window nodes controllable . You can see google The proposal .
● Reduce cookie size
cookie Transmission will cause a waste of bandwidth , Impact response time , You can do this :
Eliminate unnecessary cookies;
Static resources do not require cookie, You can use other domain names , Will not take the initiative to bring cookie.
● Avoid pictures src It's empty
picture src It's empty time , Different browsers have different side effects , Will reissue a request .
3. Performance indicators
3.1 What kind of performance indicators can truly represent the user experience ?
Think about it | The detailed content |
|---|---|
Is it happening? | Whether the navigation is successful , Whether the server responded |
Is it useful? | Whether enough content has been rendered , Let users get involved |
Is it usable? | Whether the user can interact with the page , Whether the page is busy |
Is it delightful? | Is the interaction smooth 、 natural 、 There is no lag or Caton |
Usually there are 2 There are ways to measure performance .
- Local experiments measure : Simulate the user's network locally 、 Equipment, etc . Usually when developing new functions , Experimental measurement is very important , Because we don't know what performance problems will occur when this function is released online , Therefore, the performance test shall be carried out in advance , Can be prevented .
- Online measurement : Experimental measurement can certainly reflect some problems , But it can't reflect the real situation of users . alike , At the user , Performance problems will be related to the user's equipment 、 Network conditions , It also relates to how users interact with the page . There are several types related to user perceived performance . ● Page load time : How fast the page loads and renders elements onto the page . ● Response time after loading : Page loading and execution js How long can the code respond to user interaction . ● Runtime response : After the page loads , Response time to user interaction . ● Visual stability : Whether page elements will move in a way that users do not expect , And interfere with user interaction . ● Fluency : Whether the transition and animation are rendered at a consistent frame rate , And smoothly transition from one state to another . Corresponding to the above categories ,Google and W3C The performance working group provides the corresponding performance indicators :
● First contentful paint (FCP): Measure the time when the page starts to load and a piece of content is displayed on the page .
● Largest contentful paint (LCP): Measure the time when the page starts to load and the maximum text block content or picture is displayed on the page .
● First input delay (FID): Measure the first time a user interacts with a website ( For example, click on a link 、 Button 、js Custom control ) The time until the browser actually responds .
● Time to Interactive (TTI): Measurement from page loading to visual rendering 、 Page initialization script has been loaded , And it can reliably and quickly respond to the user's time .
● Total blocking time (TBT): Measurement from FCP To TTI Time between , During this time, the main thread is blocked and cannot respond to user input .
● Cumulative layout shift (CLS): The measurement is loaded from the page until the status changes to hidden , Something unexpected happens layout shifts Cumulative score of .
These metrics can measure page performance to some extent , But not all of them are effective . for instance .LCP The main user measures whether the main content of the page has been loaded , But there will be such a situation , The biggest element is not the main content , So at this point LCP Indicators are not that important .
Each different site has its own particularity , It can be measured from the above angles , We also need to adjust measures to local conditions .
3.2 Core Web Vitals
Among the indicators listed above ,Google Defined 3 The core indicators , As Core Web Vitals. They respectively represent : load 、 Interaction 、 Visual stability .
● Largest Contentful Paint (LCP): Measure loading performance . In order to provide a better user experience ,LCP The first loading of the indicator suggestion page should be done in 2.5s Finish in .
● First Input Delay (FID): Measuring interaction performance . To provide a better user experience , The interaction time is suggested at 100ms Or within .
● Cumulative Layout Shift (CLS): Measure visual stability . To provide a better user experience , The page should be maintained CLS stay 0.1 Or within .
When page views have 75% The data of has reached above Good Standards for , I think the performance is good .
Core Web Vitals As a core performance indicator , But other indicators are also important , It is an auxiliary of the core indicators . for example ,TTFB and FCP Can be used to measure load performance ( Server response time and rendering time ), They act as LCP A problem means assistance . alike ,TBT and TTI It is also important to measure interactivity , yes FID An auxiliary of , But they can't be measured online , Nor does it reflect user centric results .
Google Officials provided one web-vitals library , The above mentioned... Can be measured online or locally 3 Indicators :
import {getCLS, getFID, getLCP} from 'web-vitals';
function sendToAnalytics(metric) {
const body = JSON.stringify(metric);
// Use `navigator.sendBeacon()` if available, falling back to `fetch()`.
(navigator.sendBeacon && navigator.sendBeacon('/analytics', body)) ||
fetch('/analytics', {body, method: 'POST', keepalive: true});
}
getCLS(sendToAnalytics);
getFID(sendToAnalytics);
getLCP(sendToAnalytics);below , Tell us about this 3 The reason for the definition of indicators 、 How to measure 、 How to optimize .
3.2.1 Largest Contentful Paint (LCP)
3.2.1.1 LCP How to define
● ( The picture is from LCP)
LCP It refers to the time when the page starts to load the maximum text block content or picture displayed in the page . So which elements can be defined as the largest element ?
<img> label
<image> stay svg Medium image label
<video> video label
● CSS background url() Loaded pictures
● Block level elements that contain inline or text
3.2.1.2 How to measure LCP
On line measuring tools
● Chrome User Experience Report
● Search Console (Core Web Vitals report)
● web-vitals JavaScript library
Laboratory tools
Native JS API measurement
LCP You can also use JS API Take measurements , The main use of PerformanceObserver Interface , At present except IE I won't support it , Other browsers basically support .
new PerformanceObserver((entryList) => {
for (const entry of entryList.getEntries()) {
console.log('LCP candidate:', entry.startTime, entry);
}
}).observe({type: 'largest-contentful-paint', buffered: true});Let's see what the result is :
Google official web-vitals library
Google The government has also provided a web-vitals library , The bottom layer still uses this API, It just helps us deal with some scenes that need to be measured and those that do not 、 And some details .
3.2.1.3 How to optimize LCP
LCP May be affected by these four factors :
● Server response time
● Javascript and CSS Caused by rendering Caton
● Resource loading time
● Client rendering
More detailed optimization suggestions will not be expanded , You can refer to here .
3.2.2 First Input Delay (FID)
3.2.2.1 FID How to define
( The picture is from FID)
We all know the importance of first impressions , For example, the impression formed by meeting someone for the first time , Will play an important role in the follow-up communication . The same is true for a website .
How fast the website is loaded and completed is one of the indicators , How fast you can respond to users after loading is also important .FID It means the latter .
You can learn more about... Through the following figure FID In which position :
( The picture is from FID)
As can be seen from the above figure , When the main thread is busy ,FID User input received from the browser , The delay time until the browser responds to the user's input .
Usually , When we're writing code , Think that as long as the user enters information , Our event callback will respond immediately , But it's not . This is because the main thread may be busy , The browser is busy parsing and executing other js. As shown in the picture above FID Time , The main thread is processing other tasks .
When FID At 100ms Or within , Then for Good.
In the example above , The user interacted at the busiest time of the main thread , But if the user interacts while the main thread is idle , Then the browser can respond immediately . therefore FID You need to focus on its distribution .
FID What is actually measured is the time that the input event is perceived as idle by the main thread . This means that even if no input event is registered ,FID It can also measure . Because the user input does not necessarily require the event to be executed , But the main thread must be idle . for example , Below these HTML All elements need to wait for the executing task on the main thread to complete before the interactive response :
● Input box , for example <input>、<textarea>、<radio>、<checkbox>
● A drop-down box , for example <select>
● link , for example <a>
Why consider measuring the first input delay ? There are the following reasons :
● Because the first input delay is the user's first impression of your website , Whether the website is of quality and reliable ;
● In today's ,web The biggest interaction problem in the first load ;
● For the website, how to solve the high first input delay ( For example, code segmentation 、 Reduce JavaScript Preload of ) The proposed solution (TTI It means measuring this piece ), It is not necessary to solve the input delay after the page is loaded (FID It means measuring this piece ) The solution is the same . therefore FID Is in TTI On the basis of more accurate subdivision .
Why? FID It just contains the corresponding time from user input to the start of the main thread ? It does not include event handling to browser rendering UI Time for ?
Although the main thread processing and drawing time is also important , But if FID Include this period of time , Developers may use asynchrony API( for example setTimeout、requestAnimationFrame) Come and put this task Split to next frame , With less FID Time for , Not only does this not improve the user experience , Instead, the user experience is reduced .
3.2.2.2 How to measure FID
FID It can be measured in the experimental environment or online .
On line measuring tools
● Chrome User Experience Report
● Search Console (Core Web Vitals report)
● web-vitals JavaScript library
Native JS API measurement
new PerformanceObserver((entryList) => {
for (const entry of entryList.getEntries()) {
const delay = entry.processingStart - entry.startTime;
console.log('FID candidate:', delay, entry);
}
}).observe({type: 'first-input', buffered: true});PerformanceObserver At present, except in IE There is no compatibility on , Other browsers are basically compatible .
Let's see what the result is :
Google official web-vitals library
Google The government has also provided a web-vitals library , The bottom layer still uses this API, It just helps us deal with some scenes that need to be measured and those that do not 、 And some details .
3.2.2.3 How to optimize FID
FID May be affected by these four factors :
● Reduce the impact of third-party code
● Reduce Javascript Execution time of
● Minimize main thread work
● Reduce the number of requests and the size of the request file
For more detailed optimization suggestions, please refer to here .
3.2.3 Cumulative Layout Shift (CLS)
3.2.3.1 CLS How to define
( The picture is from CLS)
CLS Is a very important one 、 User centered measurement indicators . It can measure whether the page layout is stable .
Page movement often occurs when resources are loaded asynchronously 、 perhaps DOM Elements are dynamically added to existing page elements . These elements may be pictures 、 video 、 Third party advertising or small icons, etc .
But we may not be aware of these problems during the development process , Because the page is refreshed during debugging , The pictures have been cached locally . When debugging the interface, we use mock Or on the LAN , The interface speed is very fast , These delays may be ignored by us .
CLS It is an indicator to help us find these problems that actually occur on the client side .
CLS Is to measure the page life cycle , Score for each unexpected layout move . When a visual element moves to another position in the next frame , This means that the layout moves .
CLS What's your score 0.1 Or below , Then for Good.
How to calculate the score of unexpected layout movement ?
The browser will monitor the unstable elements moving between the two frames . The layout move score is determined by 2 One element determines :impact fraction and distance fraction.
layout shift score = impact fraction * distance fraction
Within the visual area , The union of all unstable elements from the previous frame to the next , It will affect the layout movement score of the current frame .
for instance , In the picture below , On the left is an element of the current frame , In the next frame , The element is moved down in the visible area 25% Height . The red dashed box marks the union of the current elements in the two frames , Be palatable 75%, So at this point ,impact faction yes 0.75.
Another factor that affects the score of layout movement is distance fraction, Refers to the distance the element moves relative to the viewport . Whether it's horizontal or vertical , Taking the maximum .
In the following example , Greater vertical distance , This element moves relatively palatable 25% Distance of , therefore distance fraction yes 0.25. So the score of layout movement is 0.75 * 0.25 = 0.1875
But here's the thing , Not all layout moves are bad , quite a lot web Websites change the starting position of elements . Only when the layout movement is not expected by the user , It's not good .
let me put it another way , When the user clicks the button , The layout has been changed , This is a ok Of ,CLS Of JS API There is a field in hadRecentInput, Used to identify 500ms Whether there is user data in , As the case may be , You can ignore this calculation .
3.2.3.2 How to measure CLS
On line measuring tools
● Chrome User Experience Report
● Search Console (Core Web Vitals report)
● web-vitals JavaScript library
Laboratory tools
Native JS API measurement
let cls = 0;
new PerformanceObserver((entryList) => {
for (const entry of entryList.getEntries()) {
if (!entry.hadRecentInput) {
cls += entry.value;
console.log('Current CLS value:', cls, entry);
}
}
}).observe({type: 'layout-shift', buffered: true});Let's see what the result is :
Google official web-vitals library
Google The government has also provided a web-vitals library , The bottom layer still uses this API, It just helps us deal with some scenes that need to be measured and those that do not 、 And some details .
3.2.3.3 How to optimize CLS
We can avoid unexpected layout movement according to these principles :
● A picture or video element has a size attribute , Or give them a space size , Set up width、height, Or use unsized-media feature policy.
● Don't insert content on an existing element , In addition to the corresponding user input .
● Use animation or transition Instead of directly triggering layout changes .
More details can be found in here .
4. Performance tools : A good workman does his work well , You must sharpen your tools first
Google Developed All tools All support Core Web Vitals The measurement of . The tools are as follows :
● web.dev's Measurement tools provided
● Chrome UX Report API
These tools are good for Core Web Vitals Our support is as follows :
4.1 Lighthouse
open F12, You can see that Lighthouse, Click on Generate Report, You can generate a report . Of course, you can also add chrome The plug-in USES .
Lighthhouse It's a laboratory tool , Local simulation of mobile terminals and PC The client tests these aspects . meanwhile lighthouse Suggestions will also be made on these aspects , It is worth testing before the product goes online .
Lighthouse It also provides Lighthouse CI, hold Lighthouse Integrated into the CI In the assembly line . for instance , Every time before going online , run 50 Secondary assembly line pair Lighthouse The average value of each index is taken , Once an exception is found , Check immediately . Advance performance troubleshooting before release . I'll talk more about this later .
4.2 PageSpeed Insights
PageSpeed Insights(PSI) It is a tool that can analyze online and laboratory data . It is based on the real data of users in the online environment ( stay Chrome UX In the report ) and Lighthouse Combine a report . and Lighthouse similar , It also gives some analytical advice , You can know the page Core Web Vitals Whether it meets the standard .
PageSpeed Just provide performance tests for a single page , and Search Console It is the performance test of the whole website .
PageSpeed Insights Also provided API For our use . alike , We can also integrate it into CI in .
4.3 CrUX
Chrome UX Report (CrUX) It refers to a data report set that gathers thousands of user experience data , It is reported only with the consent of the user , Currently stored in Google BigQuery On , You can log in with your account to query . It measures all Core Web Vitals indicators .
As mentioned above PageSpeed Insights Tools are combinations CrUX The data are analyzed and the conclusions are given .
Of course CrUX Now it also provides API Let's make a query , The data that can be queried includes :
● Largest Contentful Paint
● Cumulative Layout Shift
● First Input Delay
● First Contentful Paint
The principle is as follows :
adopt API The data of the query is updated every day , And brings together the past 28 Days of data .
For specific usage, please refer to the official demo.
4.4 Chrome DevTools Performance panel
Performance It is our most commonly used local performance analysis tool .
Here are some functions you can pay attention to :Frame、Timings、Main、Layers、FPS. Let's talk about it one by one .
4.4.1 Frame
Click on Frame After deployment , You will see a red or green patch , These represent the elapsed time per frame . At present, the screen refresh rate of most devices is 60 Time / second , If the browser renders each frame of the page at the same rate as the refresh rate of the device screen , namely 60fps when , We will not be aware of the page card .
Let's move the mouse up to have a look :
This experience is smooth .
Another example :
Prompt that this frame took 30.9ms, Now it's 32fps And it is the frame dropping state .
4.4.2 Timings
Here we can see the time points of several key indicators .
● FP:First Paint;
● FCP:First Contentful Paint;
● LCP:Largest Contenful Paint;
● DCL:DOMContentLoaded Event
● L:OnLoad Event.
4.4.3 Main
Main yes DevTools The most common and important functions in .
adopt record, We can view the execution process of all operations on the page in the main thread . That is what we often call the process :
Once any process takes too long or occurs frequently , such as Update Layer Tree drawn-out 、 Frequently RecalcStyles、Layout( Redraw reflow ), So it needs attention . An example will be given later .
4.4.4 Layers
Layers It is a layer generated by the browser during the drawing process . Because the essence of browser underlying rendering is vertical layering 、 Horizontal blocking . The knowledge point of this piece occurs in Renderer Process In progress . Later, we will talk about it with an example .
Here I want to mention Layers The reason is that ,Layer Rendering of can also affect performance issues , And sometimes it's not easy to find out !
Layers Panels are not displayed by default , Click More ->more tools->Layers You can open .
Click on Layers panel , Click the lower triangle on the left to expand , You can see the composition layer finally generated by the page . You can select different latitudes to view in the upper left corner of the right .
Select a layer , You can view the reason for the generation of this layer .
Chrome Of Blink The kernel gives 54 There are three reasons why composite layers are generated :
constexpr CompositingReasonStringMap kCompositingReasonsStringMap[] = {
{CompositingReason::k3DTransform, "transform3D", "Has a 3d transform"},
{CompositingReason::kTrivial3DTransform, "trivialTransform3D",
"Has a trivial 3d transform"},
{CompositingReason::kVideo, "video", "Is an accelerated video"},
{CompositingReason::kCanvas, "canvas",
"Is an accelerated canvas, or is a display list backed canvas that was "
"promoted to a layer based on a performance heuristic."},
{CompositingReason::kPlugin, "plugin", "Is an accelerated plugin"},
{CompositingReason::kIFrame, "iFrame", "Is an accelerated iFrame"},
{CompositingReason::kSVGRoot, "SVGRoot", "Is an accelerated SVG root"},
{CompositingReason::kBackfaceVisibilityHidden, "backfaceVisibilityHidden",
"Has backface-visibility: hidden"},
{CompositingReason::kActiveTransformAnimation, "activeTransformAnimation",
"Has an active accelerated transform animation or transition"},
{CompositingReason::kActiveOpacityAnimation, "activeOpacityAnimation",
"Has an active accelerated opacity animation or transition"},
{CompositingReason::kActiveFilterAnimation, "activeFilterAnimation",
"Has an active accelerated filter animation or transition"},
{CompositingReason::kActiveBackdropFilterAnimation,
"activeBackdropFilterAnimation",
"Has an active accelerated backdrop filter animation or transition"},
{CompositingReason::kXrOverlay, "xrOverlay",
"Is DOM overlay for WebXR immersive-ar mode"},
{CompositingReason::kScrollDependentPosition, "scrollDependentPosition",
"Is fixed or sticky position"},
{CompositingReason::kOverflowScrolling, "overflowScrolling",
"Is a scrollable overflow element"},
{CompositingReason::kOverflowScrollingParent, "overflowScrollingParent",
"Scroll parent is not an ancestor"},
{CompositingReason::kOutOfFlowClipping, "outOfFlowClipping",
"Has clipping ancestor"},
{CompositingReason::kVideoOverlay, "videoOverlay",
"Is overlay controls for video"},
{CompositingReason::kWillChangeTransform, "willChangeTransform",
"Has a will-change: transform compositing hint"},
{CompositingReason::kWillChangeOpacity, "willChangeOpacity",
"Has a will-change: opacity compositing hint"},
{CompositingReason::kWillChangeFilter, "willChangeFilter",
"Has a will-change: filter compositing hint"},
{CompositingReason::kWillChangeBackdropFilter, "willChangeBackdropFilter",
"Has a will-change: backdrop-filter compositing hint"},
{CompositingReason::kWillChangeOther, "willChangeOther",
"Has a will-change compositing hint other than transform and opacity"},
{CompositingReason::kBackdropFilter, "backdropFilter",
"Has a backdrop filter"},
{CompositingReason::kBackdropFilterMask, "backdropFilterMask",
"Is a mask for backdrop filter"},
{CompositingReason::kRootScroller, "rootScroller",
"Is the document.rootScroller"},
{CompositingReason::kAssumedOverlap, "assumedOverlap",
"Might overlap other composited content"},
{CompositingReason::kOverlap, "overlap",
"Overlaps other composited content"},
{CompositingReason::kNegativeZIndexChildren, "negativeZIndexChildren",
"Parent with composited negative z-index content"},
{CompositingReason::kSquashingDisallowed, "squashingDisallowed",
"Layer was separately composited because it could not be squashed."},
{CompositingReason::kOpacityWithCompositedDescendants,
"opacityWithCompositedDescendants",
"Has opacity that needs to be applied by compositor because of composited "
"descendants"},
{CompositingReason::kMaskWithCompositedDescendants,
"maskWithCompositedDescendants",
"Has a mask that needs to be known by compositor because of composited "
"descendants"},
{CompositingReason::kReflectionWithCompositedDescendants,
"reflectionWithCompositedDescendants",
"Has a reflection that needs to be known by compositor because of "
"composited descendants"},
{CompositingReason::kFilterWithCompositedDescendants,
"filterWithCompositedDescendants",
"Has a filter effect that needs to be known by compositor because of "
"composited descendants"},
{CompositingReason::kBlendingWithCompositedDescendants,
"blendingWithCompositedDescendants",
"Has a blending effect that needs to be known by compositor because of "
"composited descendants"},
{CompositingReason::kPerspectiveWith3DDescendants,
"perspectiveWith3DDescendants",
"Has a perspective transform that needs to be known by compositor because "
"of 3d descendants"},
{CompositingReason::kPreserve3DWith3DDescendants,
"preserve3DWith3DDescendants",
"Has a preserves-3d property that needs to be known by compositor because "
"of 3d descendants"},
{CompositingReason::kIsolateCompositedDescendants,
"isolateCompositedDescendants",
"Should isolate descendants to apply a blend effect"},
{CompositingReason::kFullscreenVideoWithCompositedDescendants,
"fullscreenVideoWithCompositedDescendants",
"Is a fullscreen video element with composited descendants"},
{CompositingReason::kRoot, "root", "Is the root layer"},
{CompositingReason::kLayerForHorizontalScrollbar,
"layerForHorizontalScrollbar",
"Secondary layer, the horizontal scrollbar layer"},
{CompositingReason::kLayerForVerticalScrollbar, "layerForVerticalScrollbar",
"Secondary layer, the vertical scrollbar layer"},
{CompositingReason::kLayerForScrollCorner, "layerForScrollCorner",
"Secondary layer, the scroll corner layer"},
{CompositingReason::kLayerForScrollingContents, "layerForScrollingContents",
"Secondary layer, to house contents that can be scrolled"},
{CompositingReason::kLayerForSquashingContents, "layerForSquashingContents",
"Secondary layer, home for a group of squashable content"},
{CompositingReason::kLayerForForeground, "layerForForeground",
"Secondary layer, to contain any normal flow and positive z-index "
"contents on top of a negative z-index layer"},
{CompositingReason::kLayerForMask, "layerForMask",
"Secondary layer, to contain the mask contents"},
{CompositingReason::kLayerForDecoration, "layerForDecoration",
"Layer painted on top of other layers as decoration"},
{CompositingReason::kLayerForOther, "layerForOther",
"Layer for link highlight, frame overlay, etc."},
{CompositingReason::kBackfaceInvisibility3DAncestor,
"BackfaceInvisibility3DAncestor",
"Ancestor in same 3D rendering context has a hidden backface"},
};4.4.5 Rendering
Rendering The panel also hides many useful functions .
4.4.5.1 Paint flashing
Checked Paint flashing after , We will see what has been redrawn on the page :
4.4.5.2 Layout Shift Regions
Checked Layout Shift Regions after , Interact , You can see which elements have been moved in the layout :
4.4.5.3 Frame Rendering Stats
This tool has an episode .
Frame Rendering Stats The predecessor was FPS meter, stay Google edition 85.0.4181.0 Changed to Frame Rendering Stats, But forced by User complaints , stay 90 The version has been changed back .
Frame Rendering Stats It mainly displays the frame rate . and FPS Focus on displaying the refresh rate per second fps.
Chrome Why should I change it to no frame rate , Because I think that the frame rate can better reflect the smoothness of the page . and FPS Display the number of frames rendered per second, although it can reflect the smoothness of the page to a certain extent , But in some special cases, such as no active or idle pages ,fps It will be lower , This does not reflect the real situation .
( The picture to quote blink dev Forum discussion )
4.4.6 Memory
In large projects , Memory problems also occur .DevTools Memory analysis tools are also provided for us to use .
Click on Memory panel , Click the record button .
Click after recording , You will see the memory usage in the current state , Sort by size , We can locate places where memory is overused .
4.5 Search Console
Google Search Console In fact, it is to monitor and maintain the website Google Display in search results and troubleshooting platform . The source of the data is CrUX.
It will show 3 individual Core Web Vitals metrics: LCP, FID, CLS. If problems are found , Can cooperate with PageSpeed Use it together , To analyze problems .
( The picture to quote vital-tools)
4.6 web.dev
web.dev/measure yes google Official performance measurement tools , Will also provide similar PageSpeed Insight Indicators of , Some specific code change suggestions are also provided .
4.7 Web Vitals extension
Google It also provides extended tools to measure Core Web Vitals. It can be downloaded from Store Installation in .
4.8 Tools : Thinking and summary
When we know so many tools , Full of beautiful things in eyes , How do we choose ? How to use these tools for analysis ?
● First we can use Lighthouse, Measure locally , Optimize according to some suggestions given in the report ;
● After the release , We can use PageSpeed Insights Go and see the performance on the offline ;
● next , We can use Chrome User Experience Report API Go get the online past 28 Days of data ;
● Abnormal data found , We can use DevTools Tools for specific code positioning analysis ;
● Use Search Console's Core Web Vitals report Check the overall function of the website ;
● Use Web Vitals The expansion is convenient to see the core indicators of the page ;
5. Talk about monitoring
The last chapter is about monitoring .
When we are doing performance optimization , Often through a variety of online management , To collect user data , Perform performance analysis . you 're right , This is a means of monitoring , To be more precise , This is a kind of " After the event " Monitoring means .
" After the event " Monitoring is important , But we should also consider " In advance " monitor , otherwise , Each time a requirement is released , Go online to see the data . Why , Found that the data fell , Then we check the code , Look up the data , To find out why . In this way, students with optimized performance will always be in " chaser " Role , Always follow your ass and check problems .
for instance , We can do that " In advance " monitor .
Establish pipeline mechanism . How to do it on the assembly line ?
● Lighthouse CI or PageSpeed Insights API: hold Lighthouse or PageSpeed Insights API Integrated into the CI In the assembly line , Output report analysis .
● Puppeteer or Playwright: Use E2E Automated test tools are integrated into the pipeline to simulate user operations , obtain Chrome Trace Files, That is, we usually record Performance after , Click the file downloaded in the upper left corner .Puppeteer and Playwright The bottom is all based on Chrome DevTools Protocol.
Chrome Trace Files: according to The rules analysis Trace file , You can get the execution time of each function . If the function execution time exceeds a critical value , You can throw an exception . If the execution time of a function exceeds the critical value every time , Then it's worth noting . But one more thing to think about is : Whether the execution time of the function exceeds the critical value is important , But more importantly, this is not the user's input response function , Whether it is related to the user experience .
● The picture is from Flo Sloot Of Jank: You can measure what your users can feel.)
● Output report . Define outlier thresholds . If there are too many exceptions , Consider whether the card issuance process .
6. summary
Finally, we come to the conclusion .
Let's review the previous content :
The first part , About the overall architecture of the browser and rendering related processes , Why put this chapter in this performance optimization article ? Browsers are important for our front-end development , It's a sandbox perhaps darkbox. We know js、html、css Together, we can achieve our needs , But if you know how it is rendered 、 perform 、 Handle our code , Whether it's requirements or performance optimization , Can better understand its nature and why .
The second part , Yahoo military regulations is a very classic optimization proposal put forward many years ago . So far, it still has a strong guiding role for us . You will find that it is loaded from the page 、 Page rendering 、 A comprehensive guide to page interaction . And today Chrome and W3c Proposed Web Vitals The idea is still similar .
The third part , Performance indicators , Recommendations for reference standards and industry benchmarks , It can better guide us to optimize .
The fourth part , Performance tools . A good workman does his work well , You must sharpen your tools first . We all know that , Use good tools , So that we can get twice the result with half the effort .
The fifth part , Monitoring is an important part of performance optimization ," In advance " Monitoring is more important , Nip in the bud . Make performance optimization a preventer, not a catcher .
Laurie said a lot , Of course, there are many details about performance optimization that are not covered , If there are mistakes, please correct them . Or have what good method good suggestion, also strongly welcome the private chat exchange ~
7. At the end
Last , thank Tencent documents rose The performance optimization brought by the students to us , Tencent documents It is an online document that can be cooperated by many people , It can be edited at the same time Word、Excel and PPT file , Real time storage in the cloud , Welcome to use . As an omni-directional positioning test APP Application performance SDK, Tencent cloud QAPM Has been committed to providing first-class performance optimization services , Welcome interested students Contact us !
Reference article :
https://web.dev/learn-web-vitals/
https://developers.google.com/web/updates/2018/09/inside-browser-part1
https://aerotwist.com/blog/the-anatomy-of-a-frame/
https://www.chromium.org/developers/how-tos/getting-around-the-chrome-source-code
https://medium.com/punching-performance/jank-you-can-measure-what-your-users-can-feel-e5713df2845f
边栏推荐
- practice
- Wide measuring range of jishili electrometer
- From pair to unordered_ Map, theory +leetcode topic practice
- ESP32系列--ESP32各个系列对比
- Port conflict handling method for tongweb
- Oracle RAC configuration multipathing
- 兴业证券靠谱吗?开证券账户安全吗?
- Stm32f1 and stm32cubeide programming examples -ws2812b full color LED driver (based on spi+dma)
- `Thymeleaf ` template engine comprehensive analysis
- Is it safe to open an account in flush? What preparation is needed
猜你喜欢

Go language concurrency model mpg model

How to generate assembly code using clang in Intel syntax- How to generate assembly code with clang in Intel syntax?

Data sharing between laravel lower views

Application of motion capture system in positioning and mapping of mobile robot in underground tunnel

Overview of SAP marketing cloud functions (IV)

Explore cloud native databases and take a broad view of future technological development
Step by step introduction to sqlsugar based development framework (9) -- Realizing field permission control with WinForm control

左手代码,右手开源,开源路上的一份子

Multimeter resistance measurement diagram and precautions
![[bitbear story collection] June MVP hero story | technology practice collision realm thinking](/img/b7/ca2f8cfb124e7c68da0293624911d1.png)
[bitbear story collection] June MVP hero story | technology practice collision realm thinking
随机推荐
June training (day 24) - segment tree
Use dictionary
leetcode. 12 --- integer to Roman numeral
Brief discussion on the implementation framework of enterprise power Bi CI /cd
证券账户理财安全吗??
Security Analysis on mining trend of dogecoin, a public cloud
Overview of SAP marketing cloud functions (IV)
A brief introduction to the lexical analysis of PostgreSQL
golang中Map的并发写入
Which securities company is better and safer for great wisdom to choose when opening an account
Analysis of similarities and differences between redis and memcached in cache use
兴业证券靠谱吗?开证券账户安全吗?
R language plot visualization: use plot to visualize the training set and test set after data division, use different shape label representation, training set, test set, and display training and test
测试 H5 和小程序的区别,你真的知道吗?
Use list
Successfully solved: selenium common. exceptions. SessionNotCreatedException: Message: session not created: This versi
update+catroot+c000021a+critical service failed+drivers+intelide+viaide+000000f
09_ An efficient memory method
Linux Installation cenos7 MySQL - 8.0.26
practice