Reflow, repaint və layout thrashing
DOM və ya stil dəyişəndən sonra brauzerin gördüyü iş — style, layout, paint və compositing: hansı CSS dəyişikliyinin nəyə başa gəldiyindən tutmuş məcburi sinxron layout-a, layout thrashing-ə, ucuz animasiyalara, CSS containment-ə və DevTools-da reflow axtarmağa qədər.
Bu mövzu Junior səviyyəsindən başlayır.
Kadr pipeline-ı: dəyişiklikdən piksellərə qədər
mövzusu HTML və CSS-in ilk piksellərə qədər yolunu izləyir. Bu mövzu ondan sonra baş verənlər haqqındadır: JavaScript DOM-u və ya stili hər dəfə dəyişəndə brauzer ekranı yeniləməlidir və bunu kadr-kadr eyni mərhələlərlə edir:
- JavaScript — kodun nəyisə dəyişir: class-ı, inline stili, mətn node-unu, yeni element əlavə edir.
- Style — brauzer dəyişiklikdən hansı elementlərin təsirləndiyini müəyyən edir və onların hesablanmış stillərini yenidən hesablayır.
- Layout — yeri dəyişə biləcək qutuların ölçüsünü və mövqeyini hesablayır. Reflow layout-un digər adıdır; Chrome DevTools onu "Layout" adlandırır.
- Paint — təsirlənən hissələrin necə çəkiləcəyini qeydə alır: mətn, rənglər, border-lər, kölgələr, şəkillər. Repaint isə layout olmadan, təkcə paint-in yenidən icrasıdır.
- Composite — çəkilmiş layer-ləri birləşdirib ekranda görünən kadrı yaradır.
Hər dəyişiklik beş mərhələnin hamısından keçmir. width dəyişikliyi hamısını işə salır; color dəyişikliyi layout-u ötürür; ayrıca layer-i olan elementdə transform dəyişikliyi isə həm layout-u, həm də paint-i ötürə bilir. Hansı dəyişikliyin hansı yolla getdiyini növbəti bölmədə görəcəksən.
Kadr büdcəsi
60 Hz ekran təxminən hər 16,7 ms-dən bir, 120 Hz ekran isə hər 8,3 ms-dən bir yeni kadr göstərir. Bir kadr üçün lazım olan hər şey — sənin JavaScript-in, style, layout, paint — bu pəncərəyə sığmalıdır, üstəlik brauzerin özünə də bu vaxtın bir hissəsi lazımdır; web.dev 60 Hz üçün sənin payını təxminən 10 ms-də saxlamağı tövsiyə edir. İş sığmayanda kadrlar buraxılır: scroll ilişir, animasiyalar atlayır, yazı gecikmə ilə görünür.
Brauzer qəsdən "tənbəldir"
Stil yazmaq ucuzdur. Brauzer hər mənimsətmədən sonra səhifəni yenidən yerləşdirmir: təsirlənən hissələri köhnəlmiş ("dirty") kimi işarələyir və əsl işi növbəti render yeniləməsində bir dəfə görür:
button.addEventListener("click", () => {
panel.classList.add("open");
panel.style.width = "320px";
panel.style.padding = "16px";
});Üç yazma var, amma növbəti kadrdan əvvəl stil cəmi bir dəfə yenidən hesablanır və layout bir dəfə işləyir. Render performansı problemlərinin çoxu bu tənbəlliyi pozmaqdan yaranır: brauzeri bir tapşırığın içində layout-u dəfələrlə hesablamağa məcbur etmək, ya da hər kadrda lazım olandan çox layout və paint işi yaratmaq.
The topic follows HTML and CSS to the first pixels. This topic is about everything after that: each time JavaScript changes the DOM or a style, the browser has to bring the screen up to date, and it does so in the same stages, frame by frame:
- JavaScript — your code changes something: a class, an inline style, a text node, a new element.
- Style — the browser works out which elements are affected and recalculates their computed styles.
- Layout — it computes the size and position of the boxes that may have moved. Reflow is another name for layout; Chrome DevTools labels it "Layout".
- Paint — it records how to draw the affected parts: text, colors, borders, shadows, images. A repaint is a paint without layout before it.
- Composite — it combines the painted layers into the frame that appears on screen.
Not every change goes through all five stages. A change of width runs all of them; a change of color skips layout; a transform change on an element with its own layer can skip layout and paint. The next section shows which change takes which path.
The frame budget
A 60 Hz display shows a new frame about every 16.7 ms, a 120 Hz display every 8.3 ms. Everything for one frame — your JavaScript, style, layout, paint — has to fit into that window, and the browser needs part of it for its own work; web.dev suggests keeping your share to about 10 ms at 60 Hz. When the work does not fit, frames are dropped: scrolling stutters, animations jump, typing feels late.
The browser is lazy, on purpose
Writing styles is cheap. The browser does not lay the page out after every assignment; it marks the affected parts as out of date ("dirty") and does the real work once, in the next rendering update:
button.addEventListener("click", () => {
panel.classList.add("open");
panel.style.width = "320px";
panel.style.padding = "16px";
});Three writes, but only one style recalculation and one layout before the next frame. Most rendering performance problems come from breaking this laziness: making the browser do layout many times inside one task, or making each frame do more layout and paint than it needs.
Hansı dəyişiklik layout, paint və ya yalnız compositing tələb edir
Dəyişikliyin hansı yolla gedəcəyi onun nəyə təsir edə biləcəyindən asılıdır.
| Dəyişiklik | Nümunələr | Mərhələlər |
|---|---|---|
| Qutunun həndəsəsi | width, height, padding, margin, border-width, mövqeləndirilmiş elementdə top/left, font-size, display | style → layout → paint → composite |
| Məzmun | mətnin dəyişməsi, node əlavə etmək və ya silmək, width/height verilməmiş şəklin yüklənməsi, web şriftin əvəzedici şrifti əvəz etməsi | style → layout → paint → composite |
| Yalnız görünüş | color, background-color, box-shadow, outline, visibility | style → paint → composite |
| Compositor | ayrıca layer-i olan elementdə transform, opacity | style → composite |
Niyə ən baha mərhələ layout-dur
Layout adətən bütün sənədi əhatə edir. Bir elementi hündürləşdirmək altındakı hər şeyi aşağı itələyir, enli sidebar əsas sütunu sıxır, uzun başlıq isə ikinci sətrə keçib kartın hündürlüyünü dəyişə bilər. Brauzer kimin təsirləndiyini hesablamalıdır, böyük DOM-da isə bu vaxt aparır. Bəzi layout dəyişikliklərinə sənin CSS-in heç səbəb olmur: peyda olan scrollbar səhifənin enini dəyişir, pəncərənin ölçüsünü dəyişmək isə viewport-dan asılı olan hər şey üçün layout-u yenidən işə salır.
Paint-in qiyməti nə qədər sahənin yenidən çəkildiyindən və onu çəkməyin nə qədər baha olduğundan asılıdır: böyük box-shadow və ya filter: blur() sadə rəngdən bahadır.
Compositing ən ucuz yoldur. Element ayrıca layer-dədirsə, compositor onu layout-a və paint-ə toxunmadan, artıq çəkilmiş layer-ləri yenidən birləşdirməklə yerindən oynada, böyüdə və ya şəffaflaşdıra bilir.
Stilin yenidən hesablanması da pulsuz deyil
Hər dəyişiklik style mərhələsindən başlayır. <body>-yə class əlavə etmək səhifədəki bütün elementlərin hesablanmış stilini etibarsız edə bilər, həmin class-ı bir yarpaq elementə əlavə etmək isə yalnız o elementə təsir edir. Təsirlənən elementlər nə qədər az, selektorlar nə qədər sadə olsa, bu mərhələ bir o qədər ucuz başa gəlir.
Əzbərləmə, yoxla
Mühərriklər fərqlənir, detallar isə versiyadan versiyaya dəyişir. Məsələn, Chromium-da transform-un none-dan, opacity-nin isə 1-dən ilk dəfə dəyişməsi style və layout-u bir dəfə yenə də işə sala bilər, çünki element yeni stacking context yaratmağa başlayır; sonrakı dəyişikliklər compositor yolu ilə gedir. Siyahıya güvənmək əvəzinə DevTools-da yoxla: Rendering panelində Paint flashing (yenidən çəkilən sahələr yaşıl yanıb-sönür) və Layout Shift Regions var, Performance paneli isə hər Layout və Paint hadisəsini göstərir.
The path a change takes depends on what it can affect.
| Change | Examples | Stages |
|---|---|---|
| Box geometry | width, height, padding, margin, border-width, top/left on a positioned element, font-size, display | style → layout → paint → composite |
| Content | text changes, adding or removing nodes, an image arriving without width/height, a web font replacing the fallback | style → layout → paint → composite |
| Appearance only | color, background-color, box-shadow, outline, visibility | style → paint → composite |
| Compositor | transform, opacity on an element with its own layer | style → composite |
Why layout is the expensive one
Layout is usually scoped to the whole document. Making one element taller pushes everything below it down, a wider sidebar squeezes the main column, and a longer heading can wrap onto a second line and change the height of its card. The browser has to work out who is affected, and on a large DOM that takes time. Some layout changes are not caused by your CSS at all: a scrollbar that appears changes the width of the page, and resizing the window re-runs layout for everything that depends on the viewport.
Paint cost depends on how much area has to be repainted and how expensive it is to draw: a large box-shadow or a filter: blur() costs more than a flat color.
Compositing is the cheapest path. If an element is on its own layer, the compositor can move it, scale it or fade it by recombining layers that are already painted, without touching layout or paint.
Style recalculation is not free either
Every change starts with style. Adding a class to <body> can invalidate the computed style of every element in the page, while adding it to one leaf element affects only that element. Fewer affected elements and simpler selectors make this stage cheaper.
Check it, don't memorize it
Engines differ, and details change between versions. For example, in Chromium the first change of transform away from none, or of opacity away from 1, can still run style and layout once, because the element starts forming a new stacking context; the following changes take the compositor path. Instead of trusting a list, check in DevTools: the Rendering drawer has Paint flashing (repainted areas flash green) and Layout Shift Regions, and the Performance panel shows each Layout and Paint event.
Layout-u oxumaq onu məcbur edir: məcburi sinxron layout
Birinci bölmədəki tənbəlliyin bir istisnası var. JavaScript istənilən an həndəsəni soruşa bilər və cavab düzgün olmalıdır. Son layout-dan sonra stillər və ya DOM dəyişibsə, brauzer köhnə məlumatla cavab verə bilməz: skriptini dayandırır, stili yenidən hesablayır, layout-u elə həmin an işlədir və yalnız bundan sonra dəyəri qaytarır. Buna deyilir (Chrome onu forced reflow adlandırır).
card.classList.add("expanded");
const height = card.offsetHeight;Birinci sətir stili sadəcə köhnəlmiş kimi işarələyir. İkinci sətrə isə yeni hündürlük lazımdır, ona görə style və layout brauzerin onsuz da edəcəyi vaxtdan əvvəl, sənin tapşırığının içində işləyir.
Layout-u nə məcbur edir
Paul Irish-in Blink mənbə kodu əsasında topladığı siyahıya görə, ən çox rast gəlinənlər bunlardır:
- qutu ölçüləri:
offsetTop/Left/Width/Height,clientTop/Left/Width/Height,getBoundingClientRect(),getClientRects(); - scroll:
scrollWidth,scrollHeight,scrollTop/scrollLeft-i oxumaq və ya təyin etmək,scrollTo(),scrollBy(),scrollIntoView(); element.focus(),innerText,document.elementFromPoint(),window.scrollX/scrollYvə mouse hadisəsininoffsetX/offsetYdəyərləri;getComputedStyle(): o, stili həmişə aktual vəziyyətə gətirir,width,height,top,margin,paddingvə yatransformkimi layout-dan asılı dəyəri oxuyanda isə layout-u da məcbur edir.
element.style.width, classList, dataset, atributları və ya textContent-i oxumaq layout-u məcbur etmir: bu dəyərlər layout ağacından yox, DOM-dan gəlir.
Nə vaxt heç nəyə başa gəlmir
Oxuma yalnız nəsə köhnəlibsə bahadır. offsetWidth-i ardıcıl iki dəfə oxumaq ən çoxu bir layout-a başa gəlir; son kadrdan bəri heç nə dəyişməyibsə, oxuma keşdəki dəyəri qaytarır. "Yazmadan əvvəl oxu" məsləhəti də buradan gəlir: hadisə handler-inin əvvəlində son kadrın layout-u adətən hələ etibarlıdır.
input.addEventListener("input", () => {
const width = list.clientWidth;
list.classList.toggle("compact", width < 480);
counter.textContent = String(input.value.length);
});Bu tapşırıqda oxuma bütün yazmalardan əvvəl gəlir, ona görə son kadrdan bəri səhifəni başqa bir şey dəyişməyibsə, ucuz başa gəlir.
Tək məcburi layout nə vaxt problemə çevrilir
Tək bir məcburi layout fəlakət deyil: o, iş əlavə etmir, sadəcə onu daha erkən etdirir. Problem o, tez-tez işləyən kodda (hot path) baş verəndə yaranır — scroll handler-də, mousemove listener-də, animasiya dövründə — ya da hər məcburi layout böyük DOM-u yenidən yerləşdirəndə. Dövr içində təkrarlananda isə ciddi problemə çevrilir, bu da növbəti bölmənin mövzusudur.
The laziness from the first section has one exception. JavaScript is allowed to ask for geometry at any moment, and the answer must be correct. If styles or the DOM changed since the last layout, the browser cannot answer from stale data, so it stops your script, recalculates style, runs layout right away, and only then returns the value. That is a (Chrome calls it a forced reflow).
card.classList.add("expanded");
const height = card.offsetHeight;The first line only marks style as dirty. The second line needs the new height, so style and layout run inside your task, before the browser would have done them anyway.
What forces layout
Based on Paul Irish's list, compiled from the Blink source, the common ones are:
- box metrics:
offsetTop/Left/Width/Height,clientTop/Left/Width/Height,getBoundingClientRect(),getClientRects(); - scrolling:
scrollWidth,scrollHeight, reading or settingscrollTop/scrollLeft,scrollTo(),scrollBy(),scrollIntoView(); element.focus(),innerText,document.elementFromPoint(),window.scrollX/scrollY, and theoffsetX/offsetYof a mouse event;getComputedStyle(): it always brings style up to date, and it forces layout when you read a layout-dependent value such aswidth,height,top,margin,paddingortransform.
Reading element.style.width, classList, dataset, attributes or textContent does not force layout: these values come from the DOM, not from the layout tree.
When it costs nothing
A read is only expensive when something is dirty. Reading offsetWidth twice in a row costs one layout at most; reading it when nothing has changed since the last frame returns a cached value. That is why the advice is "read before you write": at the start of an event handler, the layout from the last frame is usually still valid.
input.addEventListener("input", () => {
const width = list.clientWidth;
list.classList.toggle("compact", width < 480);
counter.textContent = String(input.value.length);
});The read happens before any write in this task, so it is cheap unless something else changed the page since the last frame.
Why one forced layout matters
A single forced layout is not a disaster: it moves work earlier instead of adding it. It becomes a problem when it happens inside a hot path — a scroll handler, a mousemove listener, an animation loop — or when every forced layout lays out a large DOM. And it becomes a serious problem when it repeats in a loop, which is the next section.
Layout thrashing və onu necə düzəltmək olar
yazmalarla layout oxumalarını növbələşdirən dövrdür: hər iterasiya tam bir layout-un əvəzini ödəyir. Klassik nümunə sütunlu diaqramdır:
function drawChart(bars, values) {
bars.forEach((bar, i) => {
bar.style.height = `${values[i] * 2}px`;
const label = bar.querySelector(".label");
label.style.top = `${bar.offsetHeight + 4}px`;
});
}Hər bar.offsetHeight oxuması yazmadan dərhal sonra gəlir, ona görə 30 sütunlu diaqramda brauzer bir tapşırıqda səhifəni bir dəfə yox, 30 dəfə yerləşdirir. Platformadakı Layout thrash challenge-i məhz bu vəziyyətdir: hər sütunun layout-u məcbur etdiyi 30 sütunlu diaqram; onu düzəldərkən məcburi layout-ların sayını ölçürsən.
Birinci həll: artıq bildiyini oxuma
Hündürlüyü elə indicə values[i]-dən hesabladın. DOM-dan soruşmaq əvəzinə həmin ədədi istifadə et:
function drawChart(bars, values) {
bars.forEach((bar, i) => {
const height = values[i] * 2;
bar.style.height = `${height}px`;
bar.querySelector(".label").style.top = `${height + 4}px`;
});
}İkinci həll: əvvəlcə oxumaları, sonra yazmaları qruplaşdır
Ölçmələr həqiqətən lazımdırsa, əvvəlcə hamısını götür, sonra yaz. Oxumalar bir layout-u bölüşür, yazmalar isə sadəcə köhnəlmə işarəsi qoyur.
const widths = cards.map((card) => card.getBoundingClientRect().width);
cards.forEach((card, i) => {
card.style.height = `${widths[i] * 0.75}px`;
});Üçüncü həll: ölçmələri keşlə və vaxtında yenilə
Bir dəfə oxunub təkrar istifadə olunan konteyner eni pulsuzdur. Keş ölçü həqiqətən dəyişəndə yenilənməlidir. Bunun üçün taymerlə və ya dövrü ilə yoxlamaq (polling) yanlış alətdir, düzgün alət ResizeObserver-dir. Onun callback-i render yeniləməsi zamanı, layout-dan sonra və paint-dən əvvəl işləyir, ona görə yeni ölçünü əlavə layout məcbur etmədən alır:
let containerWidth = container.clientWidth;
new ResizeObserver(([entry]) => {
containerWidth = entry.contentRect.width;
}).observe(container);Callback özü layout-u dəyişirsə, brauzer həmin kadrın içində layout-u yenidən işlədir, vəziyyət sabitləşməyəndə isə "ResizeObserver loop completed with undelivered notifications" xəbərdarlığını verir.
Dördüncü həll: yazmaları requestAnimationFrame ilə planlaşdır
Oxuyub-yazan müstəqil kod hissələri çox olanda (widget-lər, plugin-lər, kitabxana və tətbiqin özü) yazmaları növbəyə yığ və bir requestAnimationFrame callback-ində icra et; FastDOM kimi kitabxanalar məhz bunu edir. Nəzərə al ki, rAF yazmaları növbəti kadra köçürür, amma callback-in içindəki "yazdıqdan sonra oxu" dövrünü düzəltmir. Üstəlik DOM-un nə vaxt yeniləndiyini dəyişir, bu da nəticəni dərhal gözləyən kod üçün vacibdir.
is a loop that alternates writes and layout reads, so every iteration pays for a full layout. A bar chart is the classic case:
function drawChart(bars, values) {
bars.forEach((bar, i) => {
bar.style.height = `${values[i] * 2}px`;
const label = bar.querySelector(".label");
label.style.top = `${bar.offsetHeight + 4}px`;
});
}Each bar.offsetHeight read comes right after a write, so with 30 bars the browser lays the page out 30 times in one task instead of once. The platform's Layout thrash challenge is exactly this situation: a 30-bar chart where every bar forces a layout, and you measure the forced layouts while fixing it.
Fix 1: don't read what you already know
The height was just computed from values[i]. Use the number instead of asking the DOM:
function drawChart(bars, values) {
bars.forEach((bar, i) => {
const height = values[i] * 2;
bar.style.height = `${height}px`;
bar.querySelector(".label").style.top = `${height + 4}px`;
});
}Fix 2: batch reads, then writes
When you do need measurements, take all of them first and write afterwards. The reads share one layout; the writes only mark things dirty.
const widths = cards.map((card) => card.getBoundingClientRect().width);
cards.forEach((card, i) => {
card.style.height = `${widths[i] * 0.75}px`;
});Fix 3: cache measurements, and invalidate them
A container width read once and reused is free. The cache must be refreshed when the size really changes. Polling with a timer or a loop is the wrong tool for that; ResizeObserver is the right one. Its callback runs during the rendering update, after layout and before paint, so it gets the new size without forcing an extra layout:
let containerWidth = container.clientWidth;
new ResizeObserver(([entry]) => {
containerWidth = entry.contentRect.width;
}).observe(container);If the callback itself changes layout, the browser runs layout again within the same frame, and it reports "ResizeObserver loop completed with undelivered notifications" when this does not settle.
Fix 4: schedule writes with requestAnimationFrame
When many independent pieces of code read and write (widgets, plugins, a library and your app), collect writes in a queue and flush them in one requestAnimationFrame callback; libraries such as FastDOM do exactly this. Note that rAF moves the writes to the next frame but does not fix a read-after-write loop inside the callback, and it changes when the DOM is updated, which matters for code that expects the result immediately.
transform və opacity animasiyası, will-change-in qiyməti
Animasiya hər kadrda baş verən dəyişiklikdir. Əgər o, left, top, width və ya height-i animasiya edirsə, hər kadr style, layout və paint-i işə salır, özü də sənin JavaScript-inin işlədiyi . Bir uzun tapşırıq — və animasiya ilişir.
transform və opacity brauzerlərin ucuz animasiya edə bildiyi iki xassədir. Element ayrıca layer-dədirsə, yeni kadr üçün yalnız lazımdır: artıq çəkilmiş layer yerini dəyişir, böyüyür və ya şəffaflaşır. Bu xassələrin CSS animasiyaları və transition-ları compositor thread-də işləyə bilir, ona görə main thread məşğul olanda belə davam edir. requestAnimationFrame-dən transform təyin edən JavaScript animasiyası da layout və paint-i ötürür, amma hər kadrda yenə main thread-ə ehtiyac duyur.
.toast-enter-bad {
animation: slide-bad 200ms ease-out;
}
@keyframes slide-bad {
from { top: -64px; }
to { top: 0; }
}
.toast-enter {
animation: slide 200ms ease-out;
}
@keyframes slide {
from { transform: translateY(-64px); opacity: 0; }
to { transform: translateY(0); opacity: 1; }
}transform layout-u dəyişmir: qonşular yerindən tərpənmir, offsetWidth isə layout qutusunu göstərməyə davam edir. Onu ucuz edən də, imkanlarını məhdudlaşdıran da elə budur. Əsl layout dəyişikliyini (siyahı elementinin yeni yerə keçməsini, kartın açılmasını) animasiya etmək üçün FLIP texnikası var: First və Last mövqeləri ölçürsən, elementi dəyişməmiş kimi göstərən tərs (Invert) transform tətbiq edirsən, sonra həmin transform-u sıfıra qaytaran transition-ı işə salırsan (Play). Layout bir dəfə dəyişir, animasiyanın özü isə compositor işidir.
will-change: qiyməti olan ipucu
will-change: transform brauzerə elementi qabaqcadan hazırlamağı deyir, adətən ona ayrıca layer verməklə; beləcə animasiyanın ilk kadrı bu işi görməli olmur. MDN onu əvvəlcədən əlavə edilən vasitə yox, mövcud performans probleminə qarşı son çarə adlandırır:
- hər layer yaddaş (GPU-da, çəkilmiş pikselləri üçün) və idarəetmə vaxtı tələb edir; yüzlərlə elementi ayrıca layer-ə çıxarmaq səhifəni, xüsusən yaddaşı az olan telefonlarda, daha da yavaşlada bilər;
- stacking context yaradan xassə ilə (
transform,opacity) yazılmışwill-changeonu dərhal yaradır, bu daz-index-in vəposition: fixedövladların davranışını dəyişə bilər; - stylesheet-də qalan
will-changeoptimallaşdırmanı həmişəlik aktiv saxlayır. Onu animasiyadan bir az əvvəl qoş və bitəndən sonra sil.
menu.addEventListener("pointerenter", () => {
menu.style.willChange = "transform";
});
menu.addEventListener("transitionend", () => {
menu.style.willChange = "auto";
});Köhnə kodda layer yaratmaq üçün transform: translateZ(0) hack-i istifadə olunur; will-change isə niyyəti birbaşa bildirir. Nəticəni DevTools-un Layers panelində yoxla: o, hər layer-i və onun niyə yarandığını göstərir.
An animation is a change on every frame. If it animates left, top, width or height, every frame runs style, layout and paint, on the , where your JavaScript also runs. One long task and the animation stutters.
transform and opacity are the two properties browsers can animate cheaply. When the element is on its own layer, a new frame only needs : the already painted layer is moved, scaled or faded. CSS animations and transitions of these properties can run on the compositor thread, so they keep going even while the main thread is busy. A JavaScript animation that sets a transform from requestAnimationFrame skips layout and paint as well, but it still needs the main thread on every frame.
.toast-enter-bad {
animation: slide-bad 200ms ease-out;
}
@keyframes slide-bad {
from { top: -64px; }
to { top: 0; }
}
.toast-enter {
animation: slide 200ms ease-out;
}
@keyframes slide {
from { transform: translateY(-64px); opacity: 0; }
to { transform: translateY(0); opacity: 1; }
}A transform does not change layout: neighbours do not move, and offsetWidth keeps reporting the layout box. That is what makes it cheap and also what limits it. To animate a real layout change (a list item moving to a new position, a card expanding), the FLIP technique measures the First and Last positions, applies an Inverting transform so the element looks unchanged, and then Plays a transition of that transform back to none. The layout changes once; the animation itself is compositor work.
will-change: a hint with a price
will-change: transform tells the browser to prepare the element in advance, typically by giving it its own layer, so the first frame of the animation does not have to do that work. MDN calls it a last resort for an existing performance problem, not something to add in advance:
- every layer costs memory (on the GPU, for its painted pixels) and management time; promoting hundreds of elements can make the page slower, especially on low-memory phones;
will-changewith a property that would create a stacking context (transform,opacity) creates it immediately, which can change howz-indexandposition: fixedchildren behave;- left in a stylesheet, it keeps the optimization alive forever. Turn it on just before the animation and remove it afterwards.
menu.addEventListener("pointerenter", () => {
menu.style.willChange = "transform";
});
menu.addEventListener("transitionend", () => {
menu.style.willChange = "auto";
});Old code uses transform: translateZ(0) as a hack to force a layer; will-change states the intent directly. Confirm the effect in the DevTools Layers panel, which shows each layer and why it was created.
CSS containment: contain və content-visibility
Layout adətən bütün sənədi əhatə edir, çünki brauzer bir widget-in içindəki dəyişikliyin səhifənin qalan hissəsinə təsir etməyəcəyini bilə bilmir. CSS containment brauzerə verilən belə bir sözdür, brauzer də ona güvənib işi məhdudlaşdırır.
contain xassəsi
contain: layout— içəridəki heç nə çöldəki layout-a təsir etmir. Element absolute və fixed övladları üçün containing block olur və stacking context yaradır.contain: paint— övladlar elementin qutusu ilə kəsilir, qutu ekrandan kənardadırsa, içindəkiləri çəkmək lazım gəlmir.contain: size— elementin ölçüsü övladlarından asılı deyil, ona görə ölçünü sən verməlisən.contain: style— counter-lər və quote-lar çölə çıxmır.- Qısa yazılışlar:
content=layout paint style(müstəqil widget-lərin çoxu üçün təhlükəsizdir);strict=contentüstəgəlsize.
.feed-item {
contain: content;
}Lent elementi, chat mesajı, şərh və ya üçüncü tərəf embed-i yaxşı namizəddir: məzmunu dəyişəndə layout və paint onun içində qala bilir. contain bütün müasir brauzerlərdə işləyir.
content-visibility: ekrandan kənardakını ötür
content-visibility: auto layout, style və paint containment-i aktivləşdirir, element viewport-dan uzaqda olduğu müddətdə isə onun məzmununu tamamilə ötürür: istifadəçi yaxına scroll edənə qədər həmin alt ağac üçün nə style, nə layout, nə də paint işləyir. Uzun səhifələrdə (məqalələr, sənədləşmə, lentlər) bu, ilkin render işinin böyük hissəsini aradan qaldıra bilər.
.article-section {
content-visibility: auto;
contain-intrinsic-size: auto 600px;
}Ötürülən element boşmuş kimi ölçülür, ona görə contain-intrinsic-size ilə ona yer tutan ölçü ver. Bu olmasa, ekrandan kənardakı bölmələrin hündürlüyü sıfıra enir, scrollbar yanlış görünür, bölmələr render olunduqca səhifə atlayır. auto açar sözü brauzerə son render olunmuş ölçünü yadda saxlamağı və bölmə yenidən ötürüləndə həmin ölçünü istifadə etməyi deyir.
content-visibility: hidden məzmunu həmişə ötürür (display: none kimi, amma render vəziyyəti saxlanılır, ona görə elementi yenidən göstərmək daha ucuzdur). auto ilə ötürülən məzmun accessibility ağacında qalır, find-in-page, fokus və tab ardıcıllığı ilə işləməyə davam edir; hidden ilə isə onu tapmaq, fokuslamaq və Tab ilə ona çatmaq olmur.
MDN content-visibility-ni Baseline 2024 kimi göstərir; Safari 26-dan əvvəlki versiyalarda auto ilə ötürülən məzmunu find-in-page tapmırdı.
Trade-off-lar
- Ötürülən alt ağacın içindəki həndəsəni oxumaq (övladın
offsetHeight-i) brauzeri onu yerləşdirməyə məcbur edir və bütün qazancı sıfırlayır. İçindəkiləri yox, konteyneri ölç. content-visibilitybütün DOM node-larını saxlayır: yaddaş və DOM ölçüsü azalmır. On minlərlə sətir üçün virtualizasiya (yalnız görünən sətirləri render etmək) yenə də düzgün alətdir; bunu List virtualization mövzusu izah edir.- Containment davranışı dəyişir (kəsilmə, stacking context, containing block), ona görə onu yalnız komponent həqiqətən müstəqil olan yerdə əlavə et.
Layout is usually document-wide because the browser cannot know that a change inside one widget will not affect the rest of the page. CSS containment is a promise that it will not, and the browser uses the promise to limit work.
The contain property
contain: layout— nothing inside affects the layout outside. The element becomes a containing block for absolute and fixed descendants and creates a stacking context.contain: paint— descendants are clipped to the element's box, and when the box is off-screen its contents need not be painted.contain: size— the element's size does not depend on its children, so you must give it a size.contain: style— counters and quotes do not leak out.- Shorthands:
content=layout paint style(safe for most independent widgets);strict=contentplussize.
.feed-item {
contain: content;
}A feed item, chat message, comment or third-party embed is a good candidate: when its content changes, layout and paint can stay inside it. contain works in all modern browsers.
content-visibility: skip what is off-screen
content-visibility: auto turns on layout, style and paint containment and, while the element is far from the viewport, skips its contents entirely: no style, layout or paint for that subtree until the user scrolls near it. On long pages (articles, documentation, long feeds) this can remove most of the initial rendering work.
.article-section {
content-visibility: auto;
contain-intrinsic-size: auto 600px;
}A skipped element is sized as if it were empty, so give it a placeholder size with contain-intrinsic-size. Without it, off-screen sections collapse to zero height, the scrollbar is wrong, and the page jumps as sections render. The auto keyword makes the browser remember the last rendered size and use it when the section is skipped again.
content-visibility: hidden always skips the contents (like display: none, but the rendering state is kept, so showing it again is cheaper). With auto, skipped content stays in the accessibility tree and still works with find-in-page, focus and tab order; with hidden it cannot be found, focused or reached with Tab.
MDN lists content-visibility as Baseline 2024; in Safari before version 26, skipped auto content was not found by find-in-page.
Trade-offs
- Reading geometry inside a skipped subtree (
offsetHeightof a child) forces the browser to lay it out, which cancels the benefit. Measure the container, not its contents. content-visibilitykeeps every DOM node: memory and DOM size stay. For tens of thousands of rows, virtualization (rendering only the visible rows) is still the tool; the List virtualization topic covers it.- Containment changes behaviour (clipping, stacking contexts, containing blocks), so add it only where a component is truly independent.
Reflow-ları DevTools-da və React tətbiqlərində tapmaq
Performance qeydini oxumaq
Yavaş qarşılıqlı əlaqəni Chrome DevTools-un Performance panelində yaz; sürətli noutbuk telefona daha çox oxşasın deyə CPU throttling-i aç. Main track-də sarı rəng scripting, bənövşəyi render (Recalculate style, Layout), yaşıl isə paint deməkdir.
- Sağlam kadr style və layout-u bir dəfə, sənin tapşırığın bitəndən sonra edir.
- Məcburi layout skriptin içində görünür: funksiya çağırışının altında yerləşən bənövşəyi Layout bloku. DevTools belə hadisələri xəbərdarlıqla işarələyir və layout-u məcbur edən JavaScript sətrinə keçid verir.
- Thrashing daraq kimi görünür: bir tapşırığın altında onlarla nazik bənövşəyi Layout bloku.
- Insights panelində Forced reflow insight-ı var (Chrome 134 və sonrakı versiyalar). O, ən çox məcburi reflow vaxtı olan funksiyanı və onun stack trace-ini göstərir; keçid meyarı 30 ms-dən uzun çəkən məcburi reflow-un olmamasıdır.
Paint üçün Rendering panelini aç: Paint flashing hər kadrda nəyin yenidən çəkildiyini, Layer borders və Layers paneli isə hansı elementlərin ayrıca layer-ə çıxarıldığını və niyə çıxarıldığını göstərir.
React qruplaşdırır, sən isə yenə poza bilərsən
React bir commit-in bütün DOM dəyişikliklərini birlikdə tətbiq edir, ona görə framework-ün özü thrashing yaratmır. Sənin kodun isə yarada bilər: useLayoutEffect React DOM-u dəyişdikdən sonra və brauzer paint etməzdən əvvəl sinxron işləyir, ona görə commit DOM-u dəyişibsə, oradakı ölçmə layout-u məcbur edir. Commit başına bir ölçmə (məsələn, tooltip-i yerləşdirmək üçün) normaldır, hook elə bunun üçündür. Problem siyahının hər sətri həm özünü ölçəndə, həm də yazanda yaranır — burada hündürlüyünü 8px-lik şəbəkəyə uyğunlaşdırmaq üçün:
import { useLayoutEffect, useRef } from "react";
function Row({ text }) {
const ref = useRef(null);
useLayoutEffect(() => {
const height = ref.current.offsetHeight;
ref.current.style.minHeight = `${Math.ceil(height / 8) * 8}px`;
});
return <li ref={ref}>{text}</li>;
}Bütün sətirlərin layout effect-ləri eyni tapşırıqda ardıcıl işləyir: ikinci sətir birinci sətrin yazmasından sonra oxuyur, üçüncü ikincidən sonra və s. Nəticədə hər sətir üçün bir məcburi layout alınır. Ölçməni valideyndə bir dəfə et, ortaq ResizeObserver istifadə et, ya da məsələni CSS ilə həll et (container query-lər, auto sətirli grid) ki, ümumiyyətlə heç nəyi ölçmək lazım olmasın.
Hər ilişmə layout deyil
Input ləng hiss oluna bilər, amma qeyddə bənövşəyi yox, sarı rəng üstünlük təşkil edir: vaxt layout-a yox, scripting-ə gedir (React tətbiqində çox vaxt hər düymə basışında çoxlu komponentin render olunmasına). Orada layout fəndləri kömək etməyəcək, skript işini azaltmaq isə edəcək. Həmişə əvvəlcə qeydə bax və üstünlük təşkil edən rəngin işini azalt. Belə qeydi oxumağı Typing lag challenge-ində məşq etmək olar. Qarşılıqlı əlaqə zamanı uzun tapşırıqlar INP-ni də pisləşdirir; bunu Core Web Vitals mövzusu izah edir.
Reading a Performance recording
Record the slow interaction in the Chrome DevTools Performance panel, with CPU throttling on so a fast laptop behaves more like a phone. In the Main track, yellow is scripting, purple is rendering (Recalculate style, Layout) and green is painting.
- A healthy frame does its style and layout once, after your task has finished.
- A forced layout shows up inside a script: a purple Layout block nested under your function call. DevTools marks such events with a warning and links to the line of JavaScript that forced them.
- Thrashing looks like a comb: dozens of narrow purple Layout blocks under one task.
- The Insights sidebar has a Forced reflow insight (Chrome 134 and later). It names the function with the most forced reflow time and its stack trace; its passing criterion is no forced reflow longer than 30 ms.
For paint, open the Rendering drawer: Paint flashing shows what is repainted on each frame, and Layer borders together with the Layers panel show which elements were promoted and why.
React does the batching, you can still break it
React applies all DOM changes of a commit together, so the framework itself does not thrash. Your code can: useLayoutEffect runs synchronously after React has changed the DOM and before the browser paints, so a measurement there forces a layout whenever the commit changed the DOM. One measurement per commit (positioning a tooltip, say) is fine and is what the hook is for. The problem appears when every row of a list measures itself and writes, here to snap its height to an 8px grid:
import { useLayoutEffect, useRef } from "react";
function Row({ text }) {
const ref = useRef(null);
useLayoutEffect(() => {
const height = ref.current.offsetHeight;
ref.current.style.minHeight = `${Math.ceil(height / 8) * 8}px`;
});
return <li ref={ref}>{text}</li>;
}Layout effects of all rows run one after another in the same task, so row 2 reads after row 1 wrote, and so on: one forced layout per row. Measure once in the parent, use a shared ResizeObserver, or solve it in CSS (container queries, grid with auto rows) so nothing has to be measured at all.
Not every jank is layout
An input can feel slow while the recording shows yellow, not purple: the time goes to scripting (in a React app, often rendering many components on every keystroke), not to layout. Layout tricks will not help there; less script work will. Always look at the recording first and reduce the work of the colour that dominates. The Typing lag challenge is a good place to practise reading such a recording. Long tasks during interactions also make INP worse, which the Core Web Vitals topic covers.
Müsahibə üçün məsləhətlər
- Terminləri dəqiq izah et. Reflow = layout: qutuların həndəsəsinin hesablanması. Repaint = layout-suz paint: həndəsəsi dəyişməyən piksellərin yenidən çəkilməsi. Compositing = çəkilmiş layer-lərin birləşdirilməsi. Hansı CSS dəyişikliyinin hansı mərhələyə qədər getdiyini de və əlavə et ki, mühərriklər fərqlənir və sən bunu DevTools-da yoxlayardın.
- Əvvəlcə tənbəlliyi, sonra istisnanı izah et. Yazmalar səhifəni sadəcə köhnəlmiş kimi işarələyir; brauzer style və layout-u kadr başına bir dəfə edir. Köhnəlmiş səhifədə həndəsəni oxumaq (
offsetHeight,getBoundingClientRect(),getComputedStyle()-in layout-dan asılı dəyərləri) bu işi dərhal məcbur edir. Layout thrashing həmin oxumanın yazmalar dövrünün içində olmasıdır. - Həlləri üstünlük sırası ilə say. Hesablaya bildiyini oxuma; oxumaları yazmalardan əvvəl qruplaşdır; ölçmələri keşlə və
ResizeObserverilə yenilə; DOM-a kodun çox hissəsi toxunanda yazmalarırequestAnimationFrameilə planlaşdır. rAF-ın vaxtlamanı dəyişdiyini, yəni pulsuz həll olmadığını da qeyd et. - Animasiyalar:
transformvəopacity-ni animasiya et, layout dəyişiklikləri üçün FLIP-dən istifadə et,will-change-i isə ümumi sürət düyməsi kimi yox, yaddaş qiyməti olan məqsədli ipucu kimi təsvir et. - Senior dərinliyi: CSS containment (
contain: content,contain-intrinsic-sizeilə birlikdəcontent-visibility: auto), onun virtualizasiya ilə müqayisədə trade-off-ları və React-inuseLayoutEffect-inin çoxlu kiçik ölçməni necə thrashing-ə çevirə bildiyi. - Necə tapacağını göstər. CPU throttling ilə Performance qeydi, skriptlərin içində yerləşən bənövşəyi Layout blokları, Forced reflow insight-ı, Paint flashing. Əvvəl və sonra ölç; rəqəm ("klik başına 30 məcburi layout idi, indi 0") "daha sürətli hiss olunur"-dan yaxşı cavabdır.
Qaçmalı olduğun yanlış ifadələr:
- "Stili dəyişmək reflow-u dərhal işə salır" — o, səhifəni köhnəlmiş kimi işarələyir; işi həndəsənin oxunması və ya növbəti kadr başladır.
- "
transformhəmişə pulsuzdur" — ona layer lazımdır, layer-lər yaddaş tutur, ilk dəyişiklik isə yenə layout-u işə sala bilər. - "
requestAnimationFramelayout thrashing-i düzəldir" — o, işi sadəcə növbəti kadra köçürür; içindəki "yazdıqdan sonra oxu" dövrü yenə thrashing yaradır. - "Hər yerdə
will-changesəhifəni sürətləndirir" — həddindən çox layer onu yavaşladır.
- Define the terms precisely. Reflow = layout: computing the geometry of boxes. Repaint = paint without layout: redrawing pixels whose geometry did not change. Compositing = combining painted layers. Say which CSS changes reach which stage, and add that engines differ and you would confirm it in DevTools.
- Explain laziness first, then the exception. Writes only mark the page dirty; the browser does style and layout once per frame. A geometry read (
offsetHeight,getBoundingClientRect(), layout-dependentgetComputedStyle()values) on a dirty page forces that work immediately. Layout thrashing is that read inside a loop of writes. - Give the fixes in order of preference. Do not read what you can compute; batch reads before writes; cache measurements and refresh them with
ResizeObserver; schedule writes withrequestAnimationFramewhen many parts of the code touch the DOM. Mention that rAF changes timing, so it is not a free fix. - Animations: animate
transformandopacity, use FLIP for layout changes, and describewill-changeas a targeted hint with a memory cost, not a global speed switch. - Senior depth: CSS containment (
contain: content,content-visibility: autowithcontain-intrinsic-size), its trade-offs against virtualization, and how React'suseLayoutEffectcan turn many small measurements into thrashing. - Show how you would find it. A Performance recording with CPU throttling, purple Layout blocks nested inside scripts, the Forced reflow insight, Paint flashing. Measure before and after; a number ("30 forced layouts per click, now 0") is a better answer than "it felt faster".
Misstatements to avoid:
- "Changing a style triggers reflow immediately" — it marks the page dirty; reading geometry or the next frame triggers the work.
- "
transformis always free" — it needs a layer, layers cost memory, and the first change can still run layout. - "
requestAnimationFramefixes layout thrashing" — it only moves work to the next frame; a read-after-write loop inside it still thrashes. - "
will-changeeverywhere makes the page faster" — too many layers make it slower.
Kodu reflow və repaint baxımından review edərkən nəyi yoxlamalı
Bu yoxlama siyahısı DOM-u və ya stilləri dəyişən, amma sənin yazmadığın kodu (komanda yoldaşının pull request-ini, kitabxanadan götürülmüş snippet-i və ya AI assistentin təklifini) review edəndə lazımdır. Yanlış yerdəki bircə həndəsə oxuması bir tapşırıqda onlarla layout-u məcbur edə bilər, nəticədə scroll və animasiyalar ilişir.
- Dövr içində həndəsə oxuması (
offsetHeight,getBoundingClientRect(),scrollTop) stil və ya DOM yazmasından sonra gəlirmi? Bu, adlanır: hər iterasiya tam bir layout-a başa gəlir. Artıq bildiyin dəyəri istifadə et, ya da əvvəlcə bütün oxumaları, sonra bütün yazmaları et. DövrürequestAnimationFrame-in içinə qoymaq onu sadəcə növbəti kadra köçürür. - Scroll və ya
mousemovehandler-ləri hər hadisədə layout oxuyurmu? Orada hər oxuma saniyədə dəfələrlə yarada bilər. Ölçünü keşlə və onu taymerlə yox,ResizeObserverilə yenilə. - Animasiya
top,left,widthvə yaheight-i dəyişirmi? Onda hər kadr layout və paint işlədir. Əvəzindətransformvəopacity-ni animasiya et və nəticəni DevTools-un Rendering panelindəki Paint flashing ilə yoxla. will-changeçoxlu elementə verilib, yaxud stylesheet-də həmişəlik qalıbmı? Hər layer yaddaş tutur, onun yaratdığı stacking context isəz-index-in işləməsini dəyişə bilər. Onu animasiyadan bir az əvvəl qoş, bitəndən sonra sil; Layers paneli bütün layer-ləri göstərir.- React-də siyahının hər sətrindəki
useLayoutEffectəvvəlcə ölçü oxuyub sonra stil yazırmı? Bu effect-lər ardıcıl işləyir, ona görə hər sətir öz layout-unu məcbur edir. Ölçməni valideyndə bir dəfə et və ya bir ortaqResizeObserveristifadə et. - Düzəliş CPU throttling ilə yazılmış "əvvəl" və "sonra" Performance qeydləri ilə sübut olunubmu? Skriptlərin içində yerləşən bənövşəyi Layout bloklarını və forced reflow xəbərdarlıqlarını axtar.
Use this list when you review code you did not write (a teammate's pull request, a library's snippet or an AI assistant's suggestion) that changes the DOM or styles. One geometry read in the wrong place can force dozens of layouts in one task, and scrolling and animations stutter.
- In a loop, does a geometry read (
offsetHeight,getBoundingClientRect(),scrollTop) follow a style or DOM write? That is : a full layout per iteration. Use the value you already know, or do all reads before all writes. Wrapping the loop inrequestAnimationFrameonly moves it to the next frame. - Do scroll or
mousemovehandlers read layout on every event? Each read there can be a , many times per second. Cache the size and refresh it with aResizeObserver, not with a timer. - Does an animation change
top,left,widthorheight? Then every frame runs layout and paint on the . Animatetransformandopacityinstead, and check with Paint flashing in the DevTools Rendering drawer. - Is
will-changeset on many elements or left in the stylesheet for good? Every layer costs memory, and its stacking context can change howz-indexworks. Add it just before an animation, remove it afterwards; the Layers panel shows every layer. - In React, does each list row's
useLayoutEffectread a size and then write a style? The effects run one after another, so every row forces its own layout. Measure once in the parent or share oneResizeObserver. - Is the fix proven by Performance recordings from before and after, with CPU throttling? Look for purple Layout blocks nested inside scripts and for forced reflow warnings.
Özünü yoxla
Təcrübədə sına
Bu mövzudan istifadə edən praktiki işlər.