1+ import snippet from ' ../../snippets/CoreWebVitals/CLS.js?raw'
2+ import { Snippet } from ' ../../components/Snippet'
3+
14# Cumulative Layout Shift (CLS)
25
36### Overview
@@ -20,64 +23,7 @@ Unexpected layout shifts are frustrating and can cause users to click the wrong
2023
2124### Snippet
2225
23- ``` js copy
24- // CLS Quick Check
25- // https://webperf-snippets.nucliweb.net
26-
27- (() => {
28- let cls = 0 ;
29-
30- const valueToRating = (score ) =>
31- score <= 0.1 ? " good" : score <= 0.25 ? " needs-improvement" : " poor" ;
32-
33- const RATING = {
34- good: { icon: " 🟢" , color: " #0CCE6A" },
35- " needs-improvement" : { icon: " 🟡" , color: " #FFA400" },
36- poor: { icon: " 🔴" , color: " #FF4E42" },
37- };
38-
39- const logCLS = () => {
40- const rating = valueToRating (cls);
41- const { icon , color } = RATING [rating];
42- console .log (
43- ` %cCLS: ${ icon} ${ cls .toFixed (4 )} (${ rating} )` ,
44- ` color: ${ color} ; font-weight: bold; font-size: 14px;`
45- );
46- };
47-
48- const observer = new PerformanceObserver ((list ) => {
49- for (const entry of list .getEntries ()) {
50- if (! entry .hadRecentInput ) {
51- cls += entry .value ;
52- }
53- }
54- logCLS ();
55- });
56-
57- observer .observe ({ type: " layout-shift" , buffered: true });
58-
59- // Update on visibility change (final CLS)
60- document .addEventListener (" visibilitychange" , () => {
61- if (document .visibilityState === " hidden" ) {
62- observer .takeRecords ();
63- console .log (" %c📊 Final CLS (on page hide):" , " font-weight: bold;" );
64- logCLS ();
65- }
66- });
67-
68- // Expose function for manual check
69- window .getCLS = () => {
70- logCLS ();
71- return cls;
72- };
73-
74- console .log (
75- " Call %cgetCLS()%c anytime to check current value." ,
76- " font-family: monospace; background: #f3f4f6; padding: 2px 4px;" ,
77- " "
78- );
79- })();
80- ```
26+ <Snippet code = { snippet } />
8127
8228### Understanding CLS
8329
0 commit comments