Interpretation of next-generation web performance experience and quality metrics

Posted May 26, 202014 min read

There are always a lot of tools and indicators to measure the experience and quality of a Web page ... Every time we pay attention to these indicators, it will be very painful, because these indicators are really many and difficult to understand. There are also many tools.

When I saw the addition of several performance indicators in the recently released Chrome 83, my head was big ...

However, do n t worry, these indicators are for focusing attention and reducing the cost of understanding. Let s take a closer look at what is the newly added Core Web Vitals?

How to measure user experience quality?

Optimizing the quality of user experience has always been the key to the long-term success of each Web site, and there are many aspects to measuring the quality of user experience. Although some aspects of the user experience need to be site-specific and context-specific, all sites still have a common set of metrics-Core Web Vitals. These metrics include loading experience, interactivity, and visual stability of page content. They form the basis of the core Web health indicators in 2020.

Over the years, Google has provided many tools:(Lighthouse, Chrome DevTools, PageSpeed Insights, Search Console's Speed Report) to measure and report performance. Some developers are experts in using these tools, while most others find it difficult to learn and use a large number of tools and metrics.

Website developers should not become performance experts in order to understand the quality indicators of the experience they deliver to users. The purpose of the Web Vitals plan is to simplify the scenario, reduce learning costs, and help the site focus on the most important indicator, namely Core Web Vitals.

Core Web Vitals

Core Web Vitals is a subset of Web Vitals that applies to all Web pages. All site developers should pay attention, they will be displayed in all the performance testing tools provided by Google. Each Core Web Vitals represents a different aspect of user experience, is measurable in this area, and reflects the true experience of user-centric key results.

The performance indicators of the core of the web page should evolve over time. The current 2020 mainly focuses on three aspects of user experience-loading, interactivity and visual stability:

  • Largest Contentful Paint(LCP):Measure loading experience:In order to provide a good user experience, LCP should occur within 2.5 seconds after the page first starts to load.
  • First Input Delay(FID):measure interactivity, in order to provide a good user experience, the page s FID should be less than 100 milliseconds.
  • Cumulative Layout Shift(CLS):To measure visual stability, in order to provide a good user experience, the CLS of the page should be kept less than 0.1.

Below we will introduce these three performance indicators in detail:

LCP

Measurement of loading experience

Measuring the loading speed of the main content of the Web page is a point that many developers have been paying attention to, and there are many measurable indicators.

For example, the earliest load and DOMContentLoaded events. It is very bad to use these two events to measure the page loading speed, because they do not necessarily correspond to what the user sees on the screen.

User-centric update performance indicators(such as First Contentful Paint(FCP)) it can only capture the very beginning of the loading experience. If the initial display of the page is a loading animation, then this indicator is difficult to follow.

Later, the industry began to recommend the use of performance indicators such as First Meaningful Paint(FMP) and Speed Index(SI)(both available in Lighthouse) to help capture more loading experiences after the initial rendering, but these The indicators are very complex and difficult to explain, and the false positive rate is relatively high.

What is LCP

Largest Contentful Paint(LCP) is used to measure the rendering time of the largest content element visible in the viewport of the standard report. In order to provide a good user experience, the website should strive to perform Maximum Content Rendering within 2.5 seconds before starting to load the page.

Compared with FCP, this indicator is very valuable, because this value is constantly changing according to the page loading and rendering. If the page has a lodaing animation, and then only the specific content is rendered, then the calculation of this indicator is the specific The loading speed of the content, not the loading speed of the lodaing animation.

What elements does LCP consider

LCP does not currently calculate all the elements, because this will make this indicator very complicated, and now it only focuses on the following elements:

  • <img> element
  • The <svg> element inside the <image> element
  • <video> element
  • Load the background image elements through the url() function
  • Block-level elements that contain text nodes or children of other inline text elements.

To keep things simple at the beginning, it is intentional to limit the elements to this limited set. With the deepening of research, more elements may be added in the future.

How to calculate LCP?

The largest element on the page is the element with the largest drawing area. The so-called drawing area can be understood as the "footprint" of each element on the screen. If the element extends outside the screen, or if the element is cut off a part, the cut Parts are not included, only those that are actually displayed on the screen are counted.

The calculation method of the area of the picture element is slightly different, because the picture can be enlarged or reduced through CSS, that is to say, the picture has two areas:" rendered area "and" real area ". In the calculation of LCP, the drawing area of the picture will get a smaller value. For example:When "Rendering Area" is smaller than "Real Area", "Drawing Area" is "Rendering Area" and vice versa.

The page is linear during the loading process, and the elements are rendered one by one on the screen, rather than being completely rendered on the screen in an instant, so the element with the largest "rendering area" changes at any time.

If an element is deleted, the LCP algorithm will no longer consider the element. If the deleted element happens to be the element with the largest "drawing area", a new performance entry is created using the new element with the largest "drawing area".

This process will continue until the first time the user scrolls the page or the first user input(mouse click, keyboard key, etc.), that is, once the user starts interacting with the page, it will stop reporting new performance indicators.

In the above two timelines, the largest element changes as the content loads. In the first example, new content is added to DOM, and the largest element is changed. In the second example, the layout is changed and the previous largest content is deleted from the viewport. Generally, the content of lazy loading is larger than the content already on the page.

Improve LCP

The most common reasons for poor LCP are:

  • Slow server response time
  • Block rendered Javascript and CSS
  • Slow resource loading time
  • Client rendering

So we consider improving LCP from the above perspective:

Optimize the server

This is easy to understand. The longer the browser takes to receive content from the server, the longer it takes to render any content on the screen. Faster server response time can directly improve all page loading indicators including LCP.

There is a special indicator to measure the corresponding time of the server:the corresponding time of the first byte(TTFB) is the period from the initial network request is initiated to the time when the first byte is received from the server, it includes the TCP connection time, The time to send the HTTP request and the time to get the first byte of the response message. You can try to optimize TTFB in the following ways:

  • Cache HTML offline pages, cache page resources and reduce browser requests for resources.
  • Minimize resource blocking rendering:CSS and JavaScript compression, merge, cascade, inline, etc.
  • Optimize the picture. Convert the format of the picture to JPG or WEBP etc., reduce the size of the picture to speed up the request.
  • Rewrite HTML, compress spaces, remove comments, etc. Reduce the size of HTML and speed it up.
  • Use preconnect to establish a link with the server as soon as possible, and use dns-prefetch to perform a DNS lookup as soon as possible.
  • Use CDN to speed up the request

Optimized resources that block rendering

JavaScript and CSS are resources that will block page rendering. You need to compress CSS and JavaScript files as much as possible, delay loading the first screen without using JavaScript, inline keyCSSWait to reduce the blocking time.

Optimize resource loading time

The resources mentioned above, if you render on the first screen, the time it takes to load these elements will directly affect the LCP.

  • <img> element
  • The <svg> element inside the <image> element
  • <video> element
  • Load the background image elements through the url() function
  • Block-level elements that contain text nodes or children of other inline text elements.

You can use the following means to optimize:

  • Optimize the picture. Convert the format of the picture to JPG or WEBP etc. format, reduce the size of the picture.
  • Preload important resources, such as adding the rel =" preload "attribute to the style` tag
  • Use Gzip and Brotli to compress page resources and reduce transmission time
  • Use service worker to cache resources

Server rendering

Using server-side rendering can ensure that the page content is first rendered on the server, which can effectively improve LCP, but the disadvantage of client-side rendering is that it will increase the page and affect TTFB. Server-side rendering needs to wait for all js to be executed Only corresponding user input can make the interactive experience worse.

FID

First impression

We all know how important it is to make a good first impression. On the Internet, a good first impression can determine whether a person can become a loyal user of a website, or whether he will never return after leaving. The question is, what makes a good impression, and how do you measure what kind of impression you might make to users?

On the Internet, the first impression can take many different forms-we have a first impression of the design and visual appeal of the website, as well as its speed and responsiveness.

Developers use First Contentful Paint(FCP) to measure the first impression of website loading speed. However, the speed at which a website can draw pixels on the screen is only part of it, and just as important is the responsiveness of your website when users try to interact with these pixels!

What is FID

FID(First Input Delay) is to record the time it takes for the user to interact with the page for the first time. The FIDindicator affects the user s first impression of the interactivity and responsiveness of the page. In order to provide a good user experience, the site should strive to make the first input delay less than100` milliseconds.

FID occurs between FCP and TTI, because at this stage, although the page already shows part of the content, it is not yet fully interactive. At this stage, there is often a large delay in user interaction with the page.

As shown in the figure above, when the browser receives user input operations, the main thread is busy performing a long-running task. Only after this task is executed can the browser respond to user input operations. The time it must wait is the user's FID value on this page.

For example, all of the following HTML elements need to wait for the ongoing tasks on the main thread to complete before responding to user interaction:

  • Text input boxes, check boxes and radio buttons(<input>, <textarea>)
  • Select the drop-down menu(<select>)
  • Link(<a>)

How to improve FID

The following aspects are important indicators for improving FID:

Reduce JavaScript execution time

The same way to improve LCP above:

  • Shrink and compress JavaScript files
  • Lazy loading of JavaScript not needed for the first screen
  • Minimize unused polyfill

Break down time-consuming tasks

As mentioned above, a long time-consuming task is an important indicator that affects FID. Any code segment that blocks the main thread for 50 milliseconds or more can be called a "long task." The task is split into smaller asynchronous tasks.

Using Web Worker

Main thread blocking is one of the main reasons for input delay. Web Workers allows you to run JavaScript on a background thread separate from the main execution thread. The advantage of this is that it can perform time-consuming processing tasks in a separate thread, allowing the main(usually UI) thread to run Without being blocked. Moving non-UI operations to a separate worker thread can reduce the blocking time of the main thread, thereby improving FID.

CLS

Visual stability

Have you ever happened the following when visiting a Web page? While reading the article, the text suddenly moved, you suddenly can't find where you are reading, when the button is clicked, the button was moved to another place, causing you to click something else?

Unexpected movement of page content usually occurs due to asynchronous loading of resources or dynamic addition of DOM elements to pages above existing content. The culprit may be an image or video of unknown size, a larger or smaller font after rendering, or a third-party advertisement or widget that dynamically adjusts its size.

Cumulative Layout Shift(CLS) can help you solve this problem by measuring the frequency of actual user occurrences.

What is CLS?

CLS will measure the sum of all individual layout change scores for each unexpected style movement that occurs during the entire life cycle of the page. The movement of the layout may occur whenever the visible element changes position from one frame to the next. In order to provide a good user experience, the website should strive to make the CLS score less than 0.1.

How to calculate CLS?

Layout offset score

To calculate the layout offset, the browser looks at the size of the viewport between the two rendered frames and the movement of unstable elements in the viewport. The layout offset score is the product of the two indicators of the movement:influence score and distance score.

layout shift score = impact fraction * distance fraction

Impact Score

The union of the visible areas of all unstable elements of the previous frame and the current frame(accounting for part of the total area of the viewport) is the impact score of the current frame.

In the image above, there is an element that occupies half of the viewport in a frame. Then, in the next frame, the element moves down by 25%of the height of the viewport. The red dotted rectangle represents the union of the visible areas of the elements in the two frames. In this case, it is 75% of the total viewport, so its impact score is 0.75.

Distance Score

Another part of the layout offset value equation measures the distance that unstable elements move relative to the viewport. The distance score is the maximum distance(horizontal or vertical) that any unstable element moves in the frame divided by the maximum size of the viewport(width or height, whichever is greater).

In the above example, the largest viewport size is height, and the unstable element has moved 25% of the viewport height, which makes the distance score 0.25.

Therefore, in this example, the impact score is 0.75 and the distance score is 0.25, so the layout displacement score is 0.75 * 0.25 = 0.1875.

How to improve CLS?

Don't use dimensionless elements

Elements such as images and videos always need to include the width and height attributes. Modern browsers will set the default aspect ratio of the image based on the width and height attributes of the image. After knowing the aspect ratio, the browser will You can calculate and reserve enough space for the elements.

Alternatively, use aspect-ratio to specify the aspect ratio in advance:

img {
    aspect-ratio:attr(width)/attr(height);
}

What about responsive pictures? You can use srcset to define images so that the browser can choose between images and the size of each image.

<img
    width = "1000"
    height = "1000"
    src = "puppy-1000.jpg"
    srcset = "puppy-1000.jpg 1000w,
            puppy-2000.jpg 2000w,
            puppy-3000.jpg 3000w "
    alt = "ConardLi"
/>
  • Never insert content above existing content unless it is in response to user interaction. This ensures the expected layout change.
  • Rather than converting animations, do not convert animations that trigger layout-changing attributes. Animate transitions in a way that provides context and continuity from one state to another.

Reserve space for ad slots in advance

Many page ads are inserted dynamically, so be sure to reserve a certain space for the ad space in advance.

Beware of font changes

Fonts are usually large files and take a while to load. Some browsers do not render text until the font is downloaded

font-display:swap tells the browser to use the system font for rendering by default, and replace it after the custom font is downloaded.

@ font-face {
  font-family:'Pacifico';
  font-style:normal;
  font-weight:400;
  src:local('Pacifico Regular'), local('Pacifico-Regular'), url(https://fonts.gstatic.com/xxx.woff2) format('woff2');
  font-display:swap;
}

In addition, you can use <link rel =" preload "> to load font files earlier.

Get Core Web Vitals

Google believes that Core Web Vitals is essential for all web experiences. Therefore, it is committed to displaying these indicators in its tools. The following is the support of indicators in existing tools:

Tools that have not yet supported these indicators will be supported recently.

web-vitals

Now you can use the standard Web API to measure each indicator in JavaScript. Google provides an npm package:web-vitals, this library provides a very simple API, measuring each indicator is as simple as calling a normal function:

npm install web-vitals

Each measurement function receives a report callback function as a parameter. The callback function will be triggered after the measurement is completed. In addition, indicators such as LCP and CLS are constantly changing, so their callback function may be Triggered multiple times, if you want to get the value of each change during this period, you can specify the second parameter reportAllChanges, otherwise the callback function will only trigger once after the final measurement is completed.

import {getCLS, getFID, getLCP} from 'web-vitals';

getCLS(console.log, true);
getFID(console.log); //Does not take a `reportAllChanges` param.
getLCP(console.log, true);

These changed indicators may be sent to your server multiple times if triggered multiple times, so the callback function provides the following three parameters:

  • name:indicator name
  • id:local analysis id
  • delta:the difference between the current value and the last value obtained

Therefore you only need to report delta(the difference between the current value and the last value obtained) each time, without reporting the new value. Then the server can obtain the final result by calculating the sum of all corresponding values of id.

import {getCLS, getFID, getLCP} from 'web-vitals';

function logDelta({name, id, delta}) {
  console.log(`${name} matching ID ${id} changed by ${delta}`);
}

getCLS(logDelta, true);
getFID(logDelta);
getLCP(logDelta, true);

You can combine Google Analytics to record your report metrics:

import {getCLS, getFID, getLCP} from 'web-vitals';

function sendToGoogleAnalytics({name, delta, id}) {
  ga('send', 'event', {
    eventCategory:'Web Vitals',
    eventAction:name,
    eventValue:Math.round(name === 'CLS'? delta * 1000:delta),
    eventLabel:id,
    nonInteraction:true,
  });
}

getCLS(sendToGoogleAnalytics);
getFID(sendToGoogleAnalytics);
getLCP(sendToGoogleAnalytics);

Using Chrome Plugin

If you do n t want to calculate in the program, you can also use the Chrome plugin as a more convenient way. Google also provides a new plugin web-vitals-extension to help us obtain these indicators:

This plug-in is very concise, with only three core indicators, CLS, FID, LCP, which can greatly focus our attention and reduce the cost of understanding.

The color of the badge can tell you whether the page has passed the threshold set by default:

  • Gray:The plugin is not supported or disabled
  • Green:pass all indicators
  • Red:One or more indicators are not up to standard

reference

summary

Finally, want to use the above tools and indicators in the browser? Hurry up and upgrade the Chrome 83 version ~, for more updates of Chrome 83, you can click Chrome 83 release, support direct reading and writing of local files! New cross-domain strategy! View.

If there is any error in the text, please correct me in the comment area. If this article helps you, please like and follow.

Want to read more high-quality articles, you can follow me githubblog , your star , likes and followers are my motivation for continuous creation!

It is recommended to follow my WeChat public account [code secret garden], push high-quality articles every day, we grow together.