Tối ưu CLS (Cumulative Layout Shift — đo mức layout bị dịch chuyển bất ngờ) bằng 4 kỹ thuật chính:
- Images/video: luôn khai báo
width+heighthoặcaspect-ratiođể browser reserve space trước khi tải xong - Dynamic content: reserve không gian cố định cho ads/embeds bằng
min-height - Web fonts: dùng
font-display: swap+size-adjusttrong@font-faceđể fallback font có kích thước gần giống font chính - Tránh inject content: không thêm nội dung mới phía trên viewport (banner notifications) vì đẩy toàn bộ nội dung xuống
To minimize CLS (which measures unexpected layout shifts), take several steps.
- First, always declare
widthandheight(oraspect-ratio) on images and videos so the browser reserves space before they load. - Second, reserve fixed space for ads, embeds, and dynamic content with
min-heightto prevent content below from shifting. - For web fonts, use
font-display: swapcombined withsize-adjustin@font-faceso the fallback font matches the primary font's dimensions, reducing the layout shift during font swap. - Finally, absolutely avoid injecting new content above the current viewport (like a notification banner) as it pushes all content downward.