Critical Rendering Path
How the browser turns HTML, CSS and JavaScript into pixels — DOM, CSSOM, render tree, layout, paint and compositing — and what blocks or speeds up the first render.
This topic starts at Junior level.
What the critical rendering path is
(Critical Rendering Path, CRP) brauzerin HTML sənədinin baytlarını aldığı andan ekranda piksellər çəkənə qədər keçdiyi addımlar zənciridir. "Kritik" sözü istifadəçi ilk mənalı məzmunu görməzdən əvvəl mütləq tamamlanmalı olan işə və resurslara aiddir.
Addımlar
- HTML → DOM. Brauzer baytları simvollara çevirir, onları token-lərə ayırır və node-lar yaradır. Bu node-lardan ağacı qurulur.
- CSS → CSSOM. Stil cədvəlləri də oxşar prosesdən keçir və nəticədə yaranır.
- Render ağacı. Brauzer DOM ilə CSSOM-u birləşdirir, hər görünən node-un yekun stilini hesablayır və qurur.
- Layout. Hər qutunun dəqiq ölçüsü və mövqeyi hesablanır (, başqa adı reflow).
- Paint. Qutular çəkmə əmrlərinə çevrilir: mətn, rənglər, sərhədlər, kölgələr, şəkillər ().
- Composite. Çəkilmiş layer-lər son kadrda birləşdirilir ().
Ardıcıllıq niyə vacibdir
Hər addım özündən əvvəlkilərdən asılıdır. Render ağacı olmadan layout başlaya bilməz, render ağacı üçün isə həm DOM, həm də CSSOM lazımdır. Ona görə də girişlərdən birini ləngidən hər şey — yavaş yüklənən stil faylı, HTML parser-i dayandıran skript — ilk paint-i bütövlükdə gecikdirir. CRP-ni optimallaşdırmaq bu zənciri ilk ekran üçün qısaltmaq deməkdir: render-i bloklayan resursları, baytları və şəbəkə gediş-gəlişlərini (round trip) azaltmaq.
Brauzer həm də hissə-hissə işləyir. O, bütün HTML faylının gəlməsini gözləmir: artıq gələn hissəni təhlil edir və səhifənin yuxarı hissəsini tez render edə bilir.
Təkcə ilk yükləmə deyil
Bu pipeline bir dəfə işləyib bitmir. Səhifə göstərildikdən sonra JavaScript-in etdiyi hər DOM və ya stil dəyişikliyi onun bir hissəsini yenidən işə salır: style, layout, paint, composite. Yəni eyni bilik həm səhifəni tez yükləməyə, həm də interaksiyaları və animasiyaları axıcı saxlamağa kömək edir.
The (CRP) is the chain of steps the browser goes through between receiving the bytes of an HTML document and drawing pixels on the screen. "Critical" refers to the work and the resources that must be finished before the user sees the first meaningful content.
The steps
- HTML → DOM. The browser decodes the bytes into characters, splits them into tokens and creates nodes. The nodes form the tree.
- CSS → CSSOM. Stylesheets go through a similar process and produce the .
- Render tree. The browser combines the DOM and the CSSOM, computes the final style of every visible node and builds the .
- Layout. It calculates the exact size and position of every box (, also called reflow).
- Paint. It turns the boxes into drawing instructions: text, colors, borders, shadows, images ().
- Composite. It combines the painted layers into the final frame ().
Why the order matters
Each step depends on the previous ones. Layout cannot start before the render tree exists, and the render tree needs both the DOM and the CSSOM. So anything that delays one of the inputs — a slow stylesheet, a script that stops the HTML parser — delays the first paint as a whole. Optimizing the CRP means shortening this chain for the first screen: fewer resources that block rendering, fewer bytes, fewer network round trips.
The browser also works incrementally. It does not wait for the whole HTML file: it parses what has already arrived and can render the top of the page early.
Not only the first load
The pipeline does not run just once. After the page is shown, every DOM or style change made by JavaScript re-runs part of it: style, layout, paint, composite. The same knowledge helps you both load pages faster and keep interactions and animations smooth.
Building the DOM and the CSSOM
HTML parser hissə-hissə qurur: şəbəkədən HTML parçaları gəldikcə ağaca yeni node-lar əlavə olunur. Parser <link rel="stylesheet">, <img> və ya <script src> ilə qarşılaşanda brauzer həmin resursları sorğulamağa başlayır.
Stil cədvəlləri çevrilir. Burada brauzer başqa cür davranır: yarımçıq yüklənmiş stil faylı render üçün yararsızdır, çünki faylın sonundakı qayda əvvəlindəki qaydanı üstələyə bilər — kaskad məhz belə işləyir. Ona görə brauzer stil faylı tam yüklənib təhlil olunana qədər gözləyir.
CSS render-i bloklayır
Default olaraq <head> içindəki stil cədvəlləri : onlar yüklənməyincə brauzer səhifəni render etmir. Əks halda istifadəçi əvvəlcə stilsiz məzmunu görər, sonra isə səhifə birdən yekun görünüşünə "sıçrayardı" (FOUC — flash of unstyled content).
CSS-in nəyi bloklamadığına diqqət et: HTML parser işini davam etdirir, DOM böyüməkdə davam edir. Yalnız render gözləyir.
media atributu bu davranışı dəyişir. Media sorğusu cari mühitə uyğun gəlməyən stil faylı yenə də yüklənir (adətən aşağı prioritetlə), amma render-i bloklamır:
<link rel="stylesheet" href="main.css" />
<link rel="stylesheet" href="print.css" media="print" />
<link rel="stylesheet" href="wide.css" media="(min-width: 1024px)" />Burada main.css render-i həmişə bloklayır, print.css ekranda heç vaxt bloklamır, wide.css isə yalnız viewport ən azı 1024px enində olanda bloklayır.
Praktiki nəticələr
- Stil fayllarını
<head>-ə yerləşdir ki, tez aşkarlansınlar. - İlk ekran üçün lazım olan CSS-i kiçik saxla: onun hər kilobaytı ilk paint-i gecikdirir.
- CSS daxilində
@import-dan qaç. İmport olunan fayl yalnız əsas fayl yüklənib təhlil olunandan sonra aşkarlanır və bu, zəncirə daha bir gediş-gəliş əlavə edir.
The HTML parser builds the incrementally: as chunks of HTML arrive over the network, new nodes are added to the tree. When the parser meets <link rel="stylesheet">, <img> or <script src>, the browser starts requesting those resources.
Stylesheets are parsed into the . Here the browser behaves differently: a half-loaded stylesheet is useless for rendering, because a rule at the end of the file can override a rule at the start — that is how the cascade works. So the browser waits until the whole stylesheet is downloaded and parsed.
CSS is render-blocking
By default, stylesheets in the <head> are : the browser does not render the page until they have loaded. Otherwise the user would first see unstyled content, and then the page would jump into its final look (FOUC — flash of unstyled content).
Note what CSS does not block: the HTML parser keeps going and the DOM keeps growing. Only rendering waits.
The media attribute changes this. A stylesheet whose media query does not match the current environment is still downloaded (usually with low priority), but it does not block rendering:
<link rel="stylesheet" href="main.css" />
<link rel="stylesheet" href="print.css" media="print" />
<link rel="stylesheet" href="wide.css" media="(min-width: 1024px)" />Here main.css always blocks rendering, print.css never does on a screen, and wide.css blocks only when the viewport is at least 1024px wide.
Practical consequences
- Put stylesheets in the
<head>so they are discovered early. - Keep the CSS needed for the first screen small: every kilobyte of it delays the first paint.
- Avoid
@importinside CSS. The imported file is discovered only after the parent file has been downloaded and parsed, which adds one more round trip to the chain.
Render tree, layout and paint
DOM ilə CSSOM-u birləşdirir, amma ona yalnız həqiqətən render olunacaq hissələr düşür. (Chromium-da bu ağac layout tree adlanır.)
Render ağacına daxil olmur:
<head>,<script>,<meta>,<link>və brauzerin default stilləri ilə gizlədilən digər elementlər;display: noneolan elementlər — bütün övladları ilə birlikdə.
Render ağacına daxildir:
visibility: hiddenvə yaopacity: 0olan elementlər — görünmürlər, amma yer tuturlar;content-i olan::beforevə::afterpsevdo-elementləri — DOM-da yoxdurlar, lakin qutu yaradırlar.
| Stil | DOM-da | Render ağacında | Yer tutur |
|---|---|---|---|
display: none | bəli | xeyr | xeyr |
visibility: hidden | bəli | bəli | bəli |
opacity: 0 | bəli | bəli | bəli |
Bunu JavaScript-dən də görmək olar: display: none olan elementin qutusu yoxdur, ona görə də həndəsəsi sıfırdır.
const menu = document.querySelector(".menu");
menu.style.display = "none";
console.log(menu.offsetWidth); // 0Layout, paint, composite
render ağacını gəzir və hər qutunun həndəsəsini hesablayır: enini, hündürlüyünü, mövqeyini. Faizlər, mətnin sətirlərə bölünməsi və şrift ölçüləri məhz burada həll olunur. Viewport-un ölçüsü dəyişəndə layout yenidən işləyir.
hər qutunun necə çəkiləcəyini qeydə alır: fon, sərhəd, mətn, kölgə, şəkil. Səhifə çox vaxt bir neçə layer-də çəkilir.
həmin layer-ləri düzgün ardıcıllıqla birləşdirib ekranda gördüyün kadrı yaradır. Bəzi elementlər — məsələn, animasiya olunan transform-u olan element və ya <video> — çox vaxt ayrıca layer alır və buna görə də səhifənin qalan hissəsini yenidən çəkmədən hərəkət edə bilir.
Bu pipeline ekrana ilk dəfə hər hansı mətn və ya şəkil çıxaranda brauzer anını qeydə alır.
The combines the DOM and the CSSOM, but it contains only what will actually be rendered. (In Chromium it is called the layout tree.)
Not in the render tree:
<head>,<script>,<meta>,<link>and other elements hidden by the browser's default styles;- elements with
display: none— together with all their descendants.
In the render tree:
- elements with
visibility: hiddenoropacity: 0— they are invisible but still take up space; ::beforeand::afterpseudo-elements withcontent— they are not in the DOM, yet they generate boxes.
| Style | In the DOM | In the render tree | Takes up space |
|---|---|---|---|
display: none | yes | no | no |
visibility: hidden | yes | yes | yes |
opacity: 0 | yes | yes | yes |
You can observe this from JavaScript: an element with display: none has no box, so its geometry is zero.
const menu = document.querySelector(".menu");
menu.style.display = "none";
console.log(menu.offsetWidth); // 0Layout, paint, composite
walks the render tree and calculates the geometry of every box: width, height, position. Percentages, line wrapping and font sizes are resolved here. When the viewport size changes, layout runs again.
records how to draw each box: backgrounds, borders, text, shadows, images. The page is often painted in several layers.
puts those layers together in the right order to produce the frame you see. Some elements — for example, one with an animated transform, or a <video> — often get their own layer, so they can move without repainting the rest of the page.
The first time this pipeline puts any text or image on the screen, the browser records .
Scripts, the parser and the preload scanner
Atributsuz klassik <script> . Parser ona çatanda DOM-un qurulması dayanır. Xarici skript üçün brauzer əvvəlcə onun yüklənməsini gözləyir, sonra skripti icra edir və təhlilə yalnız bundan sonra davam edir. Səbəb sadədir: skript təhlil olunan sənədi dəyişə bilər (məsələn, document.write ilə), ona görə parser təhlükəsiz şəkildə irəli gedə bilməz.
Skriptlər CSS-i gözləyir
Skript stilləri oxuya bilər (getComputedStyle, offsetWidth). Buna görə brauzer parser-in icra etdiyi skripti (inline və ya xarici, async olmadan) sənəddə ondan əvvəl gələn stil faylı hələ yüklənərkən işə salmır. Deməli, yavaş stil faylı və ondan sonra gələn skript təkcə render-i deyil, təhlili də bloklayır.
async, defer və modullar
| Skript | Yüklənmə | İcra | Ardıcıllıq |
|---|---|---|---|
<script src> | parser-i bloklayır | yüklənən kimi dərhal | sənəddəki sıra ilə |
async | paralel | yüklənən kimi (icra zamanı təhlil dayanır) | zəmanət yoxdur |
defer | paralel | təhlil bitəndən sonra, DOMContentLoaded-dan əvvəl | sənəddəki sıra ilə |
type="module" | paralel, import-ları ilə birlikdə | default olaraq təxirə salınır; async icazəlidir | async olmadan sənəddəki sıra ilə |
async və defer yalnız xarici klassik skriptlərdə işləyir; inline klassik skriptdə onlar nəzərə alınmır. Modul skriptləri isə — istər inline, istər xarici — default olaraq təxirə salınır.
DOMContentLoaded HTML tam təhlil olunanda və defer skriptləri icra olunandan sonra baş verir. O, şəkilləri və async skriptləri gözləmir. load hadisəsi isə bütün alt resursları, o cümlədən şəkilləri və stil fayllarını gözləyir.
Preload scanner
Əsas parser skript tərəfindən bloklananda brauzer boş dayanmır. xam HTML-də irəliyə baxır və tapdığı resursları yükləməyə başlayır: <img>, <link rel="stylesheet">, <script src>. Bu, brauzerin ən mühüm optimallaşdırmalarından biridir, amma o, yalnız HTML markup-da yazılanları görür. Onun aşkarlaya bilmədikləri:
- JavaScript-in əlavə etdiyi resurslar (client-də render olunan tətbiqin yaratdığı hər şey daxil olmaqla);
- CSS-də göstərilən
background-imageURL-ləri və şriftlər; - real URL-i skript onu dəyişənə qədər
data-src-də gizlənən şəkillər.
Belə gec aşkarlanan resurslar yavaş ilk render-in ən çox rast gəlinən səbəblərindəndir.
A classic <script> without attributes is . When the parser reaches it, DOM construction stops. For an external script the browser waits for the download, executes the script and only then continues parsing. The reason: the script may change the document that is being parsed (for example, with document.write), so the parser cannot safely move on.
Scripts wait for CSS
A script may read styles (getComputedStyle, offsetWidth), so the browser does not run a script that the parser executes (inline or external, without async) while a stylesheet earlier in the document is still loading. A slow stylesheet followed by a script therefore blocks not only rendering but parsing too.
async, defer and modules
| Script | Download | Execution | Order |
|---|---|---|---|
<script src> | blocks the parser | right after download | document order |
async | in parallel | as soon as downloaded (parsing pauses while it runs) | not guaranteed |
defer | in parallel | after parsing, before DOMContentLoaded | document order |
type="module" | in parallel, with its imports | deferred by default; async is allowed | document order without async |
async and defer only work on external classic scripts; on an inline classic script they are ignored. Module scripts, inline or external, are deferred by default.
DOMContentLoaded fires when the HTML is fully parsed and deferred scripts have run. It does not wait for images or async scripts. The load event waits for all subresources, including images and stylesheets.
The preload scanner
While the main parser is blocked by a script, the browser does not sit idle. The reads ahead in the raw HTML and starts downloading the resources it finds: <img>, <link rel="stylesheet">, <script src>. It is one of the most important browser optimizations, but it only sees what is written in the HTML markup. It cannot discover:
- resources added by JavaScript (including everything a client-rendered app creates);
background-imageURLs and fonts referenced in CSS;- images whose real URL hides in
data-srcuntil a script swaps it in.
These late-discovered resources are a common reason for a slow first render.
Updates after load: layout, paint, compositing
İlk render-dən sonra pipeline işləməyə davam edir. Nəsə dəyişəndə brauzer növbəti kadrdan əvvəl bu mərhələlərin bir hissəsindən keçir: JavaScript → style → layout → paint → composite. Hansı mərhələlərin işləyəcəyi nəyin dəyişdiyindən asılıdır:
| Dəyişiklik | Nümunə xassələr | Mərhələlər |
|---|---|---|
| Həndəsə | width, height, margin, padding, top, font-size, node əlavə etmək | style → layout → paint → composite |
| Yalnız görünüş | color, background-color, box-shadow | style → paint → composite |
| Transform / opacity | transform, opacity | çox vaxt yalnız composite |
Adətən ən baha mərhələ layout-dur: bir elementin ölçüsünü dəyişmək onun qonşularını, valideynini və övladlarını yerindən oynada bilər. transform və opacity dəyişikliklərini isə, element ayrıca layer-dədirsə, çox vaxt təkcə compositor emal edə bilir. Detallar brauzer mühərrikindən asılıdır, ona görə siyahı əzbərləmək əvəzinə DevTools-da yoxla.
Render və event loop
Render tapşırıqların arasında baş verir. Tapşırıq və onun bütün bitəndən sonra brauzer render-i yeniləyə bilər: callback-lərini icra edir, stil və layout-u yenidən hesablayır, sonra paint edir. uzun tapşırıq o deməkdir ki, o bitənə qədər yeni kadr olmayacaq.
Məcburi sinxron layout
Adətən layout "tənbəl" işləyir: sən stilləri dəyişirsən, brauzer isə layout-u növbəti kadrdan əvvəl bir dəfə hesablayır. Lakin JavaScript stil dəyişikliyindən sonra həndəsəni oxuyursa — offsetWidth, offsetHeight, getBoundingClientRect(), scrollTop, getComputedStyle()-dan layout-dan asılı dəyərlər — brauzer düzgün dəyər qaytarmaq üçün layout-u dərhal hesablamalı olur. Buna deyilir.
Bunu dövr içində etmək yaradır:
for (const item of items) {
item.style.width = `${container.offsetWidth / 2}px`;
}Burada hər oxuma yazmadan sonra gəlir, ona görə layout hər iterasiyada işləyir. Düzgün variant — əvvəlcə bir dəfə oxumaq, sonra yalnız yazmaq:
const half = container.offsetWidth / 2;
for (const item of items) {
item.style.width = `${half}px`;
}Qayda belədir: əvvəlcə bütün oxumaları, sonra bütün yazmaları topla; vizual yazmaları isə requestAnimationFrame ilə planlaşdır. DevTools-un Performance panelində məcburi reflow-lar xəbərdarlıqla işarələnir.
After the first render the pipeline keeps running. When something changes, the browser goes through some of these stages before the next frame: JavaScript → style → layout → paint → composite. Which stages run depends on what changed:
| Change | Example properties | Stages |
|---|---|---|
| Geometry | width, height, margin, padding, top, font-size, adding nodes | style → layout → paint → composite |
| Appearance only | color, background-color, box-shadow | style → paint → composite |
| Transform / opacity | transform, opacity | often composite only |
Layout is usually the most expensive part: resizing one element can move its siblings, its parent and its children. transform and opacity changes can often be handled by the compositor alone when the element is on its own layer. The details differ between engines, so check them in DevTools instead of memorizing lists.
Rendering and the event loop
Rendering happens between tasks. After a task and all its finish, the browser may update the rendering: it runs callbacks, recalculates style and layout, then paints. A long task on the means no new frame until it ends.
Forced synchronous layout
Normally layout is lazy: you change styles, and the browser computes layout once, before the next frame. But if JavaScript reads geometry after a style change — offsetWidth, offsetHeight, getBoundingClientRect(), scrollTop, layout-dependent values from getComputedStyle() — the browser must run layout immediately to return a correct value. This is a .
Doing it in a loop is :
for (const item of items) {
item.style.width = `${container.offsetWidth / 2}px`;
}Every read follows a write, so layout runs on every iteration. Read once, then only write:
const half = container.offsetWidth / 2;
for (const item of items) {
item.style.width = `${half}px`;
}The rule: batch reads first, then writes, and schedule visual writes with requestAnimationFrame. The DevTools Performance panel marks forced reflows with a warning.
Common pitfalls
<head>-də bloklayan skriptlər.defer-siz<script src>fayl yüklənib icra olunana qədər təhlili dayandırır; bu müddətdə istifadəçi boş səhifəyə baxır.defervə yatype="module"istifadə et.async-in sıranı qoruyacağını gözləmək.asyncskriptlər yüklənən kimi icra olunur. Əgərplugin.jslibrary.js-dən asılıdırsa, hər ikisiniasyncetmək təsadüfi "library is not defined" xətalarına gətirib çıxarır. Bir-birindən asılı skriptlər üçündeferseç.- CSS-də
@importzəncirləri. Hər@importardıcıl daha bir sorğu əlavə edir: brauzer övlad faylı yalnız valideyn fayl təhlil olunandan sonra aşkarlayır. - JavaScript hazır olana qədər səhifəni gizlətmək. Skriptin sonradan sildiyi
body { opacity: 0 }kimi pattern-lər brauzeri görünməz səhifə çəkməyə məcbur edir; məzmun faktiki olaraq yalnız skript işləyəndə görünür. - Ekranın yuxarısındakı şəkilləri lazy-load etmək. Hero şəklinə
loading="lazy"vermək onun sorğusunu brauzer layout-dan sonra şəklin viewport-a yaxın olduğunu bilənə qədər təxirə salır. Bu, adətən pisləşdirir. - Dövrlərdə və scroll handler-lərində layout ölçmək. Dövr içində stili dəyişib dərhal
offsetHeightoxumaq yaradır. - Həndəsəni animasiya etmək.
top,left,widthvə yaheightanimasiyası hər kadrda layout işlədir. Mümkün olduqdatransformvəopacity-ni animasiya et. display: none-u "pulsuz" saymaq. Element render olunmur, amma DOM-da qalır, içindəki<img>isə adətən yenə də yüklənir.DOMContentLoaded-u performans metriki kimi istifadə etmək. O, istifadəçinin nə gördüyünü deyil, təhlilin bitdiyini bildirir. İstifadəçi təcrübəsi üçün və LCP-yə bax.
- Blocking scripts in the
<head>. A<script src>withoutdeferstops parsing until the file is downloaded and executed; meanwhile the user stares at a blank page. Usedeferortype="module". - Expecting
asyncto keep the order.asyncscripts run as soon as they are downloaded. Ifplugin.jsdepends onlibrary.js, making bothasyncleads to random "library is not defined" errors. Usedeferfor scripts that depend on each other. @importchains in CSS. Every@importadds a sequential request: the browser discovers the child file only after parsing the parent.- Hiding the page until JavaScript is ready. Patterns like
body { opacity: 0 }removed later by a script make the browser paint an invisible page; the content effectively appears only when the script runs. - Lazy-loading above-the-fold images.
loading="lazy"on the hero image delays its request until the browser knows, after layout, that the image is near the viewport. This typically hurts . - Measuring layout in loops and scroll handlers. Changing styles and then reading
offsetHeightin a loop causes . - Animating geometry. Animating
top,left,widthorheightruns layout on every frame. Animatetransformandopacitywhen possible. - Treating
display: noneas free. The element is not rendered, but it is still in the DOM, and an<img>inside it is typically still downloaded. - Using
DOMContentLoadedas a performance metric. It tells you that parsing finished, not what the user sees. For that, look at and LCP.
Optimizing the critical rendering path
CRP-ni üç göstərici təsvir edir: kritik resursların sayı (render-i və ya parser-i bloklayanlar), onların cəmi olan kritik baytlar və kritik yolun uzunluğu — neçə ardıcıl şəbəkə gediş-gəlişinin lazım olduğu (HTML → CSS → @import → şrift dörd addımdır). Hər optimallaşdırma bunlardan birini azaldır. HTML-in özü üçün isə serverin tez cavab verməsi, sıxılma (Brotli və ya gzip), HTTP keşləmə və CDN baytları və gediş-gəlişləri azaldır.
CSS və JavaScript
- — ilk ekran üçün lazım olan qaydaları —
<head>-dəki<style>-a yerləşdir, qalanını isə bloklamadan yüklə. Bunun qiyməti var: inline CSS ayrıca keşlənmir və hər HTML cavabı ilə yenidən göndərilir, ona görə onu kiçik saxla və alətlərlə generasiya et. - CSS-i
media-ya görə böl ki, uyğun gəlməyən fayllar render-i bloklamasın. - Tətbiq kodu üçün
defervə yatype="module", müstəqil üçüncü tərəf skriptləri üçünasyncistifadə et. İlk paint-dən əvvəl daha az JavaScript göndər: əvvəlcə icra olunmalı olan hər şey məşğul edir.
Aşkarlanma və prioritet
<link rel="preload">CSS və ya JavaScript içində gizlənən resursları brauzerə erkən göstərir: əsas şrifti və ya elementi olan fon şəklini.- LCP şəklinə
fetchpriority="high"ver. Brauzer layout-dan əvvəl hansı şəklin LCP olacağını bilə bilmir, ona görə belə şəkillər çox vaxt aşağı prioritetlə başlayır. - Ekranın yuxarısındakı şəkilləri heç vaxt lazy-load etmə. Kritik üçüncü tərəf domenlərinə
preconnectet.
Hər şeyi preload etmə: preload-lar bandwidth uğrunda həqiqətən kritik resurslarla rəqabət aparır, Chrome isə preload olunmuş resurs load hadisəsindən bir neçə saniyə sonra da istifadə olunmayanda konsolda xəbərdarlıq verir.
Şriftlər
Brauzer şrifti yalnız render olunan hansısa mətnin ondan istifadə etdiyini biləndə, yəni stil hesablamasından sonra yükləməyə başlayır. İlk ekranın ehtiyac duyduğu bir-iki şrifti preload et (şrift preload-u crossorigin tələb edir). font-display: swap mətni dərhal əvəzedici şriftlə göstərir və şrift gələndə onu dəyişir; optional isə şriftə çox qısa vaxt verir, çatmasa əvəzedici şrift qalır — bu da gec layout sürüşməsinin qarşısını alır.
<head>
<style>/* critical rules */</style>
<link rel="preload" href="/fonts/inter.woff2" as="font" type="font/woff2" crossorigin />
<link rel="stylesheet" href="/css/main.css" media="print" onload="this.media='all'" />
<script src="/js/app.js" defer></script>
</head>
<body>
<img src="/img/hero.avif" alt="Product photo" width="1200" height="600" fetchpriority="high" />
</body>media="print" + onload pattern-i main.css-i render-i bloklamadan yükləyir və fayl yüklənəndən sonra onu tətbiq edir.
Three numbers describe a CRP: the number of critical resources (render- or parser-blocking), the critical bytes they add up to, and the critical path length — how many sequential network round trips are needed (HTML → CSS → @import → font is four). Every optimization reduces one of them. For the HTML itself, a fast server response, compression (Brotli or gzip), HTTP caching and a CDN cut bytes and round trips.
CSS and JavaScript
- Inline the — the rules needed for the first screen — in a
<style>in the<head>, and load the rest without blocking. The trade-off: inlined CSS is not cached separately and is sent with every HTML response, so keep it small and generate it with tooling. - Split CSS by
mediaso files that don't match don't block rendering. - Use
deferortype="module"for application code andasyncfor independent third-party scripts. Ship less JavaScript before the first paint: whatever has to run first occupies the .
Discovery and priority
<link rel="preload">exposes resources hidden in CSS or JavaScript to the browser early: the main font, or a background image that is the element.- Put
fetchpriority="high"on the LCP image. The browser cannot know which image is the LCP one before layout, so such images often start at a lower priority. - Never lazy-load above-the-fold images.
preconnectto critical third-party origins.
Don't preload everything: preloads compete for bandwidth with truly critical resources, and Chrome warns in the console when a preloaded resource is not used within a few seconds of the load event.
Fonts
Browsers start downloading a font only once they know that rendered text uses it, i.e. after style calculation. Preload the one or two fonts the first screen needs (font preloads require crossorigin). font-display: swap shows fallback text immediately and swaps in the font when it arrives; optional gives the font a very short window and otherwise keeps the fallback, which avoids a late layout shift.
<head>
<style>/* critical rules */</style>
<link rel="preload" href="/fonts/inter.woff2" as="font" type="font/woff2" crossorigin />
<link rel="stylesheet" href="/css/main.css" media="print" onload="this.media='all'" />
<script src="/js/app.js" defer></script>
</head>
<body>
<img src="/img/hero.avif" alt="Product photo" width="1200" height="600" fetchpriority="high" />
</body>The media="print" + onload pattern downloads main.css without blocking rendering and applies it once it has loaded.
React and the critical rendering path
Yalnız client-də render
Client-də render olunan tətbiqdə (məsələn, Vite SPA-da createRoot) HTML faktiki olaraq <div id="root"></div> və bir skriptdən ibarətdir. CRP belə olur: HTML → bundle-ın yüklənməsi → onun təhlili və icrası → React render edir → DOM → layout → paint. və bütün bundle-ı gözləyir, LCP şəkli isə üçün görünməzdir, çünki <img> yalnız React işləyəndən sonra yaranır.
SSR və streaming
Server render-də (renderToPipeableStream / renderToReadableStream və ya Next.js kimi framework) məzmun artıq HTML-in içindədir, ona görə brauzer onu heç bir JavaScript yüklənmədən çəkə bilir. <Suspense> ilə React əvvəlcə shell-i stream edir, qalan HTML-i isə sonra, fallback-i əvəz edən inline skriptlə birlikdə göndərir.
Bunun qiyməti -dır: hydrateRoot komponent kodunu yükləməli və event handler-ləri bağlamaq üçün onu client-də yenidən render etməlidir. O vaxta qədər səhifə hazır görünür, amma reaksiya vermir; hydration-un özü də ağac böyüdükcə artan main thread işidir. Suspense sərhədləri React-ə səhifəni bir dəfəyə deyil, hissə-hissə hydrate etməyə imkan verir.
React 19 resurs API-ləri
react-dom preload (resursu yükləmək), preinit (skripti yükləyib icra etmək və ya stil faylını yükləyib sənədə əlavə etmək), preconnect və prefetchDNS funksiyalarını export edir. Server render-də onlar yalnız komponentin render-i zamanı çağırılanda təsir göstərir və HTML-də teq-lərə çevrilir; brauzerdə isə onları istənilən yerdə, məsələn, naviqasiyadan əvvəl klik handler-ində çağırmaq olar.
precedence prop-u olan <link rel="stylesheet"> xüsusi davranış alır: React onu harada render olunmasından asılı olmayaraq <head>-ə yerləşdirir, href-ə görə dublikatları aradan qaldırır və stil fayllarını precedence-ə görə sıralayır. SSR zamanı o, <head>-ə daxil edilir, yəni brauzer o yüklənənə qədər paint etmir; client-də isə komponent stil faylı yüklənərkən suspend olur.
import { preinit, preload } from "react-dom";
type Props = { title: string; imageUrl: string };
export function ProductHero({ title, imageUrl }: Props) {
preload("/fonts/inter.woff2", { as: "font", type: "font/woff2", crossOrigin: "anonymous" });
preinit("https://widgets.example.com/reviews.js", { as: "script" });
return (
<section>
<link rel="stylesheet" href="/css/hero.css" precedence="default" />
<h1>{title}</h1>
<img src={imageUrl} alt={title} fetchPriority="high" />
</section>
);
}Client-only rendering
In a client-rendered app (createRoot in a Vite SPA, for example) the HTML is basically <div id="root"></div> plus a script. The CRP becomes: HTML → download the bundle → parse and execute it → React renders → DOM → layout → paint. and wait for the whole bundle, and the LCP image is invisible to the because the <img> only exists after React has run.
SSR and streaming
With server rendering (renderToPipeableStream / renderToReadableStream, or a framework such as Next.js) the content is in the HTML, so the browser can paint it before any JavaScript loads. With <Suspense>, React streams the shell first and sends the remaining HTML later, together with an inline script that replaces the fallback.
The price is : hydrateRoot must download the component code and render it again on the client to attach event handlers. Until then the page looks ready but doesn't respond, and hydration itself is main-thread work that grows with the size of the tree. Suspense boundaries let React hydrate parts of the page independently instead of all at once.
React 19 resource APIs
react-dom exports preload (fetch a resource), preinit (fetch and execute a script, or fetch and insert a stylesheet), preconnect and prefetchDNS. In server rendering they only have an effect when called while rendering a component, and they end up as tags in the HTML; in the browser they can be called anywhere — for example, in a click handler before navigating.
A <link rel="stylesheet"> with a precedence prop gets special treatment: React places it in the <head> wherever it is rendered, de-duplicates it by href and orders stylesheets by precedence. During SSR it is included in the <head>, so the browser won't paint until it has loaded; on the client, the component suspends while the stylesheet is loading.
import { preinit, preload } from "react-dom";
type Props = { title: string; imageUrl: string };
export function ProductHero({ title, imageUrl }: Props) {
preload("/fonts/inter.woff2", { as: "font", type: "font/woff2", crossOrigin: "anonymous" });
preinit("https://widgets.example.com/reviews.js", { as: "script" });
return (
<section>
<link rel="stylesheet" href="/css/hero.css" precedence="default" />
<h1>{title}</h1>
<img src={imageUrl} alt={title} fetchPriority="high" />
</section>
);
}Interview tips
- Mərhələləri ardıcıllıqla say və nəyin nəyi blokladığını izah et. HTML → DOM, CSS → CSSOM, render ağacı, layout, paint, composite. Qısa xülasə: CSS render-i bloklayır; klassik skriptlər təhlili bloklayır; CSS skriptlərin icrasını da ləngidir, ona görə yavaş stil faylı təhlili dolayı yolla bloklaya bilər.
- Yükləməni runtime-dan ayır. CRP ilk render haqqındadır, amma eyni pipeline (style → layout → paint → composite) hər yeniləmədə işləyir. , və
transformanimasiyalarınıntopvə yawidthanimasiyasından niyə ucuz olduğu barədə danışmağa hazır ol. - Təxmindən yox, ölçmədən başla. Yavaş səhifə üçün: laboratoriya rəqəmlərini və render-i bloklayan sorğuların siyahısını almaq üçün Lighthouse işlət; FCP və LCP işarələrini, uzun tapşırıqları və layout hadisələrini görmək üçün səhifəni DevTools-un Performance panelində yaz; sorğu zəncirlərini və prioritetləri Network panelinin waterfall-unda yoxla. Sonra nəticəni field data ilə müqayisə et (CrUX,
web-vitalskitabxanası), çünki laboratoriya ölçüsü real istifadəçilərin təcrübəsi deyil. - LCP-ni hissələrə böl. LCP = ilk bayta qədər vaxt (TTFB) + resursun yüklənmə gecikməsi + resursun yüklənmə müddəti + elementin render gecikməsi. Ən böyük hissə həlli göstərir: yavaş server, gec aşkarlanan şəkil, ağır şəkil və ya CSS və JavaScript tərəfindən bloklanan render. Yaxşı 2,5 saniyə və ya daha azdır və səhifə yükləmələrinin 75-ci persentilində ölçülür.
- Trade-off-lardan danış. Inline critical CSS və keşləmə; SSR (daha tez ilk paint) və hydration xərci; preload və bandwidth rəqabəti;
font-display: swapvə layout sürüşməsi. - Tipik yanlış ifadələrdən qaç: "CSS HTML təhlilini bloklayır" (o, render-i və skript icrasını bloklayır), "
asyncvədefereynidir", "display: noneiləvisibility: hiddeneyni şeydir".
- Name the stages in order and say what blocks what. HTML → DOM, CSS → CSSOM, render tree, layout, paint, composite. A compact summary: CSS blocks rendering; classic scripts block parsing; CSS also delays script execution, so a slow stylesheet can block parsing indirectly.
- Separate load from runtime. The CRP is about the first render, but the same pipeline (style → layout → paint → composite) runs on every update. Be ready to discuss , and why
transformanimations are cheaper than animatingtoporwidth. - Start from measurements, not guesses. For a slow page: run Lighthouse for lab numbers and its list of render-blocking requests; record the page in the DevTools Performance panel to see the FCP and LCP markers, long tasks and layout events; check the Network panel waterfall for request chains and priorities. Then compare with field data (CrUX, the
web-vitalslibrary), because a lab run is not your real users. - Break LCP down. LCP = time to first byte + resource load delay + resource load duration + element render delay. The largest part points to the fix: a slow server, a late-discovered image, a heavy image, or rendering blocked by CSS and JavaScript. A good is 2.5 seconds or less, measured at the 75th percentile of page loads.
- Talk about trade-offs. Inlined critical CSS vs caching; SSR (faster first paint) vs hydration cost; preloading vs bandwidth contention;
font-display: swapvs layout shift. - Avoid common misstatements: "CSS blocks HTML parsing" (it blocks rendering and script execution), "
asyncanddeferare the same", "display: noneandvisibility: hiddenare equivalent".
What to check when reviewing changes to the critical rendering path
Bu yoxlama siyahısı sənin yazmadığın və <head>-ə, skriptlərə, stil fayllarına, şriftlərə və ya ilk ekrandakı şəkillərə toxunan dəyişikliyi (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. Bircə bloklayan skript və ya gec tapılan hero şəkli istifadəçini boş səhifəyə baxmağa məcbur edə bilər.
- Hər yeni
<script src>-dədefer,asyncvə yatype="module"varmı, bir-birindən asılı skriptlər isəasyncyox,deferilə yüklənirmi? Bunlarsız klassik skript : o yüklənib icra olunana qədər təhlil dayanır.asyncskriptlər yüklənən kimi işləyir, ona görə plugin öz kitabxanasından əvvəl işə düşə bilər. - İlk ekrandakı əsas şəkil HTML-də real
<img>-dirmi və ondaloading="lazy"yoxdurmu? yalnız markup-ı görür: JavaScript-in əlavə etdiyi və ya CSS-dəbackground-imagekimi verilən şəkli görmür, lazy loading isə layout-u gözləyir. LCP elementini DevTools-un Performance panelində tap və onafetchpriority="high"ver. - Dəyişiklik
@import, böyük stil faylı və yamedia-sız print CSS-i əlavə edirmi?<head>-dəki stil faylları , hər@importisə zəncirə daha bir gediş-gəliş qatır. Render-i bloklayan sorğuların siyahısını Lighthouse göstərir. - İlk ekrana lazım olan, CSS və ya JavaScript içində gizlənən şriftlər və şəkillər preload olunubmu, özü də yalnız onlarmı? Şrift preload-u
crossorigintələb edir. Lazımsız preload-lar bandwidth uğrunda rəqabət aparır, istifadə olunmayanlar üçün isə Chrome konsolda xəbərdarlıq verir. - Səhifə skript işləyənə qədər gizlədilirmi? JavaScript-in sonradan sildiyi
body { opacity: 0 }ilə məzmun yalnız skript işləyəndən sonra görünür. - React tətbiqində ilk ekranın məzmunu serverdə render olunan HTML-dən yalnız client-də render-ə keçirmi? Onda və bütün bundle-ı gözləyir.
- Qazanc
DOMContentLoadedilə yox, FCP və LCP ilə ölçülübmü? Bu hadisə yalnız təhlilin bitdiyini bildirir. Dəyişiklikdən əvvəlki və sonrakı Performance qeydlərini müqayisə et.
Use this list when you review a change you did not write (a teammate's pull request, a library's snippet or an AI assistant's suggestion) to the <head>, scripts, stylesheets, fonts or first-screen images. One blocking script or a late-found hero image can leave users staring at a blank page.
- Does every new
<script src>havedefer,asyncortype="module", and are scripts that depend on each otherdefer, notasync? Without them, a classic script is : parsing stops until it downloads and runs.asyncscripts run as soon as they arrive, so a plugin can run before its library. - Is the main first-screen image a real
<img>in the HTML, withoutloading="lazy"? The sees only markup, not images added by JavaScript or a CSSbackground-image, and lazy loading waits for layout. Find the LCP element in the Performance panel; give itfetchpriority="high". - Does the change add
@import, a large stylesheet, or print CSS withoutmedia? Stylesheets in the<head>are , and each@importadds a round trip. Lighthouse lists the render-blocking requests. - Are fonts and images hidden in CSS or JavaScript that the first screen needs preloaded, and only those? Font preloads need
crossorigin. Extra preloads compete for bandwidth; Chrome warns about unused ones. - Is the page hidden until a script runs? With
body { opacity: 0 }removed by JavaScript, the content appears only once the script runs. - In a React app, does first-screen content move from server-rendered HTML to client-only rendering? Then and wait for the whole bundle.
- Is the gain measured with FCP and LCP, not
DOMContentLoaded? That event only says parsing finished. Compare Performance recordings before and after.
Check your understanding
Practise this
Hands-on work that uses this topic.