Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to improve CLS

2025-01-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article is mainly about "how to improve CLS". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to improve CLS.

Cumulative layout displacement (CLS) is an important user-centered measure of user visual stability because it helps to quantify the frequency of page layout changes when a user opens a page. It is currently officially recommended that this indicator should be less than 0.1, and such a CLS helps ensure the user experience of the page.

Imagine a scenario where you want to click a link or a button, but at the moment your finger falls (BOOM), the link moves and you end up clicking on something else! Isn't this a terrible experience? For example, the following examples:

Changes in page layout are usually caused by asynchronously loaded resources or the dynamic addition of DOM elements to pages above existing content. The culprit may be images or videos of unknown size, or third-party advertisements or widgets that dynamically resize themselves.

The difficulty in solving this problem is that the function of a website in development is usually very different from the user experience. The performance of personalized or third-party content in the development environment is different from that in production. Resources such as images at the time of development usually already exist in the developer's browser cache, and local API calls are usually fast, so the delay is not obvious.

On the other hand, the cumulative layout displacement (CLS) metric can help you identify such problems by measuring the frequency of changes in the actual user.

What is CLS?

CLS is the sum of scores that measure the changes in the layout of each element over the life cycle of the page.

Layout movement is defined by Layout Instability API, which defines elements visible in viewports that are considered unstable when they change their start position between two rendered frames.

Note that layout movement occurs only when an existing element changes its starting position. If a new element is added to the DOM or an existing element is resized, the element does not count as a layout offset as long as the change does not cause other visible elements to change their starting position.

What is a good CLS score?

In order to provide a good user experience, the website should strive to make the CLS score no more than 0.1. To ensure that most users achieve this goal, 75% of the pages on mobile and desktop devices that meet the requirements can be used as the basic criteria.

To learn more about the research and methodology behind this recommendation, see: defining the core Web Vitals (web.dev/defining-co …

Influence score

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

Layout shift score = impact fraction * distance fraction

Impact score

The impact score measures the impact of the variable element on the page viewport between rendered frames. The union of the visible regions of all unstable elements of the previous frame and the current frame (as part of the total area of the viewport) is the influence score of the current frame.

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

Distance score

The distance fraction is the maximum distance at which the unstable element moves in the viewport (horizontal or vertical) divided by the maximum size of the viewport (width or height, whichever is larger).

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

So, in this example, the influence score is 0.75 and the distance score is 0.25, so the layout shift score is 0.75 * 0.25 = 0.1875.

How adding content to an existing element affects the layout shift score

"Click Me!" The button is added to the bottom of the gray box with black text, and it pushes the green box with white text down (and partially out of the viewport).

In this example, the gray box changes size, but its starting position does not change, so it is not an unstable element. The button was not previously in the DOM, so its starting position does not change.

However, the starting position of the green square does change, but because it has partially moved out of the viewport, the invisible area is not taken into account when calculating the impact score. The union of the visible area of the green box (represented by a red dotted rectangle) in the two frames is the same as the area of the green box in the 50% viewport in the first frame. The impact score is 0.5.

The distance score is represented by a purple arrow. The green box has moved down about 14% of the viewports, so the distance score is 0.14.

The score of layout displacement is 0.5 x 0.14 = 0.07.

Multiple unstable elements

In the first frame above, there are four results of an animal's API request, sorted alphabetically. In the second frame, more results are added to the sorted list.

The first item in the list ("Cat") does not change its starting position between frames, so it is stable. Similarly, new items added to the list were not previously in DOM, so their starting position does not change. But items marked "dog", "horse" and "zebra" all change their starting position, making them unstable elements.

The red dotted rectangle once again represents the combination of the front and back regions of the three unstable elements, which in this case is about 38% of the viewport area (the impact rate is 0.38).

The arrow indicates the distance at which the unstable element moves from the starting position. The "zebra" element represented by the blue arrow moves the most, moving about 30% of the viewport height. The distance score in this example is 0.3.

The score of layout displacement is 0.38x0.3 = 0.1172.

Unexpected layout changes expected for VS

Not all layout changes are bad. In fact, many dynamic web applications often change the starting position of elements on a page.

The layout change is bad only if the user does not expect it. In addition, layout changes that occur in response to a user interaction (clicking a link, pressing a button, entering a search box, etc.) are usually good, as long as the change occurs close enough to the interaction. The user can clearly see the relationship.

Animation and transitions are good ways to update the content of a page and won't surprise users. Sudden movement of content on a page almost always leads to a bad user experience. However, content that moves gradually and naturally from one location to another can often help users better understand what is going on.

The CSS transform attribute allows you to animate elements without triggering layout shifts, such as using transform: scale () instead of changing the height and width attributes. To move an element, avoid changing the top, right, bottom, or left attributes, and use transform: translate () instead.

How to measure CLS

1. You can use lighthouse and performce to detect CLS.

2. Manual measurement

You can use layout instability API. Create a PerformanceObserver that listens for unexpected layout movement elements, accumulates them, and logs them to the console.

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})

How to improve CLS

First of all, the most common factors that affect CLS scores are:

A picture with no specified size

Unspecified size ads, embedded elements, iframe

Dynamically insert content

Custom font (raises FOIT/FOUT)

Wait for the network response before updating the DOM

Therefore, the improvement methods are as follows:

Set the size of the picture at the beginning, or reserve enough space. This ensures that the browser can allocate the correct amount of space in the document when loading the image. You can also use the unsize-media feature policy to enforce this behavior in browsers that support the feature policy.

Do not insert content above existing content unless you respond to user interaction. This ensures that any layout shift can be expected.

Priority is given to transforming animation attributes over animation attributes that trigger layout changes. Animate the transition to provide context and continuity between states.

Load web fonts as early as possible to avoid producing FOIT and FOUT

Work with UI colleagues to avoid layout deviation in interaction

At this point, I believe you have a deeper understanding of "how to improve CLS". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

  • If in html determines what the browser version code is.

    Editor to share with you what the html if browser version of the code, I believe that most people do not know much, so share this article for your reference, I hope you will learn a lot after reading this article, let's go to know it!

    © 2024 shulou.com SLNews company. All rights reserved.

    12
    Report