completefrontend
Open lab My progress
THE WEB PERFORMANCE FIELD GUIDE

DOM size

Why every element costs style, layout and memory, how to measure DOM size, and how content-visibility, containment and virtual lists let Chrome render less.

By the end, you can
  • 01
    Measure what a big page costsCount a page's elements and read its style, layout and memory cost as the page grows.
  • 02
    Let the browser skip workUse content-visibility and containment, and know what skipping costs and what still works.
  • 03
    Pick the right toolChoose between a full page, content-visibility and a virtual list, and know what each one breaks.

Three reviews on screen, 1,000 in the page

Asha opens Leaf and Kettle's mint tea reviews on her phone. Ravi's page still shows all 1,000 reviews, one under another. Her screen has room for three.

For a moment, the screen stays white. Then the first three reviews appear. Here is what she saw, in real frames from Chrome, and what Chrome did in between:

Two real frames of Asha's phone as Ravi's reviews page loads. At 5.6 ms, the screen is still blank. At 217.6 ms, it shows the first three reviews. Below, the main thread while the page loaded, to scale: parsing the HTML, then Recalculate style for 6,015 elements in 19.2 ms, then Layout for 12,017 layout objects in 97.8 ms, then pre-paint and paint.5.6 ms: still blank217.6 ms: three reviewsAsha's phone just after she opened the page: an empty white screen.The first frame of Ravi's page: the Leaf and Kettle header, the title Mint tea reviews, and the reviews by Asha, Ravi and Meera.Recalculate style: 6,015 elements, 19.2 msparse HTMLLayout: 12,017 objects, 97.8 mspre-paint, paintAsha opens the page, 0 msfirst frame, 217.6 ms
Real frames from the course's recording in Chrome. Below them, the main thread while the page loaded, to scale. The longest step, shaded, was layout: every box of all 1,000 reviews, before Asha could see three.

Here are the main numbers as code:

Asha opens Ravi's pagePop out in the code editor (opens in a new tab)JavaScript
// Asha opens Ravi's reviews page, from Chrome's trace.// Times are in milliseconds (ms) after the page started loading.const load = { firstFrame: 217.6, onScreen: 3, styled: 6015, styleMs: 19.2, layoutObjects: 12017, layoutMs: 97.8 }; console.log(`Asha saw her first ${load.onScreen} reviews at ${load.firstFrame} ms.`);console.log(`Before that, Chrome styled ${load.styled} elements in ${load.styleMs} ms.`);console.log(`It laid out ${load.layoutObjects} layout objects in ${load.layoutMs} ms.`);
  • Lines 1 and 2 are comments. A millisecond (ms) is a thousandth of a second.
  • Line 3 holds what Chrome's trace recorded. A trace is Chrome's detailed record of everything it did, as in lesson 7.2.
  • Line 5 prints Asha saw her first 3 reviews at 217.6 ms.
  • Line 6 prints Before that, Chrome styled 6015 elements in 19.2 ms. Line 7 prints It laid out 12017 layout objects in 97.8 ms.

You met both steps in lesson 31.1 and lesson 31.2. Recalculate style works out the final styles of every element. Layout works out the size and place of every box. Chrome keeps a box for each element it shows, and for each piece of text. These boxes are called layout objects.

Now look at the counts. Asha could see three reviews. Before showing them, Chrome styled and laid out all 1,000. So Ravi has three questions. What does each review cost? Can Chrome skip the ones nobody can see? And what if they weren't in the page at all? This lesson answers all three, with real recordings.

Real-life analogyA café that lays every table for three guests

Three friends walk into a big café for tea. Before they can sit, the staff lay every table in the building: cups, plates, spoons, a menu. There are 1,000 tables. The friends wait while 997 empty tables get laid, and the cupboards run low.

In real life: The 1,000 tables
In JavaScript: The 1,000 reviews in the page
In real life: The three tables with guests
In JavaScript: The three reviews on Asha's screen
In real life: Laying one table
In JavaScript: Styling and laying out one review
In real life: Cupboard space for every cup
In JavaScript: Memory for every element

Every element and every piece of text in a page is a node of its DOM, the page's tree of elements. A page's DOM size is how many nodes, or elements, it holds.

The main idea

Chrome styles, lays out and keeps in memory every element in the page, on the screen or not. The more elements, the more work. So render less: let Chrome skip what's far from the screen, or keep it out of the page.

How the course recorded it

  • The browser: Chrome 157, on a screen the size of Asha's phone: 412 by 823 px. Its processor, the CPU, was slowed 4 times, as in lesson 31.2.
  • The pages: Ravi's page from lesson 31.2, with 100, 1,000, 2,500 or 5,000 reviews. Then the same 1,000 reviews, drawn in other ways.
  • The loads: each page was loaded 5 times, taking turns. The course kept the load with the middle first paint.
  • The changes: each change was made 9 times, from the page's own JavaScript. The course kept the middle one.
  • The times: they come from the course's own computer, so yours will differ. The counts of elements and layout objects won't.

What every review costs: style, layout and memory

To see what one review costs, the course built Ravi's page four times: with 100, 1,000, 2,500 and 5,000 reviews. Then it made two changes from the earlier lessons:

  • Night reading, from lesson 31.1, changes every colour. Chrome has to restyle the whole page.
  • A narrower column, from lesson 31.2, changes every review's width. Chrome has to lay out the whole page again.

It also measured memory. After a clean-up of unused memory, it read two numbers through the DevTools protocol: the commands DevTools uses to talk to a page. Lesson 29.2 did the same. The two numbers are:

  • The JS heap: the memory that holds the page's JavaScript objects.
  • Blink's heap: the memory that Blink, Chrome's rendering engine, keeps for the page. The DOM lives there, and so do its layout objects. The DOM entry from lesson 29.3 measures part of it.
Ravi's page at three sizesPop out in the code editor (opens in a new tab)JavaScript
// Ravi's page at three sizes. Middle of 9 changes each.const pages = [  { reviews: 100, nightMs: 3.1, narrowerMs: 4.4, blinkMB: 1.5 },  { reviews: 1000, nightMs: 24.5, narrowerMs: 35.4, blinkMB: 11.5 },  { reviews: 5000, nightMs: 117.9, narrowerMs: 167.1, blinkMB: 56.2 },];for (const p of pages) {  console.log(`${p.reviews} reviews: Night reading ${p.nightMs} ms, narrower column ${p.narrowerMs} ms, Blink heap ${p.blinkMB} MB`);}
  • Lines 3 to 5 hold three of the sizes. Each has Night reading's style time, the narrower column's layout time, and Blink's heap. A megabyte (MB) is a million bytes.
  • Line 8 prints one line per size. The first is 100 reviews: Night reading 3.1 ms, narrower column 4.4 ms, Blink heap 1.5 MB.
  • Then 1000 reviews: Night reading 24.5 ms, narrower column 35.4 ms, Blink heap 11.5 MB.
  • The last is 5000 reviews: Night reading 117.9 ms, narrower column 167.1 ms, Blink heap 56.2 MB.
Two changes on Ravi's page at four sizes, to scale, with Blink's heap. 100 reviews: Recalculate style 3.1 ms after Night reading, Layout 4.4 ms after the narrower column, Blink heap 1.5 MB. 1,000 reviews: Recalculate style 24.5 ms after Night reading, Layout 35.4 ms after the narrower column, Blink heap 11.5 MB. 2,500 reviews: Recalculate style 61 ms after Night reading, Layout 89 ms after the narrower column, Blink heap 28.3 MB. 5,000 reviews: Recalculate style 117.9 ms after Night reading, Layout 167.1 ms after the narrower column, Blink heap 56.2 MB.Recalculate style, Night readingLayout, narrower columnBlink heap100 reviews3.1 ms4.4 ms1.5 MB1,000 reviews24.5 ms35.4 ms11.5 MB2,500 reviews61 ms89 ms28.3 MB5,000 reviews117.9 ms167.1 ms56.2 MB
Plain bars: Recalculate style after Night reading. Shaded bars: Layout after the column got narrower. Each grows with the number of reviews, and so does the memory on the right.

Every number grew with the reviews. Five times the reviews cost almost five times the style, the layout and the memory. It's like painting a fence: twice the fence takes twice the paint, whether anyone looks at the far end or not. On Ravi's page, each review added about 11 KB to Blink's heap. A kilobyte (KB) is a thousand bytes.

The JS heap didn't move. It stayed at 0.72 MB at every size. Why it matters: a big DOM's memory sits in Blink's heap, not in your JavaScript. Look for it there.

And the time? Lesson 26.1 showed that INP, roughly a visit's slowest tap, is good at 200 ms or less. With 5,000 reviews, Night reading spent 117.9 ms on style alone. That's more than half of it, before any script or paint.

Measuring a page's DOM size

Here are three ways, from quick to thorough:

  • In the console, document.querySelectorAll("*").length counts the elements, as lesson 28.2 showed. Ravi's 1,000-review page has 6,018.
  • DevTools' Performance monitor shows DOM nodes, live. Nodes count the text too, so the same page has 12,041.
  • The Performance panel's Optimize DOM size insight reads a trace. It shows the total elements, the DOM depth (how deeply elements nest), and the element with the most children. Lighthouse 13 shows the same insight.

The insight only fails when a big page was also slow. Lesson 28.2 gave its rule: a Layout of more than 100 layout objects, or a Recalculate style of more than 300 elements, that took 40 ms or more. On the 1,000-review page, it flagged one step of the load: the Layout of 12,017 objects, 97.8 ms. With 100 reviews, it passed.

Older versions of Lighthouse had an audit called Avoid an excessive DOM size. It warned when the body held more than about 800 nodes. Lighthouse 13 replaced it with this insight, which doesn't count toward the score. Why it matters: a count alone doesn't make a page slow. Slow style and layout do.

Compare the four sizes:

Playground: Ravi's page at four sizes
What the course measuredJavaScript
// Ravi's page with 1,000 reviews
document.querySelectorAll("*").length;
document.querySelector("#night").click();
document.querySelector("main").style.maxWidth = "360px";
1,000 reviewsRecorded
Night reading: Recalculate style24.5 ms, 6,008 elements
Narrower column: Layout35.4 ms, 12,017 objects
Blink heap11.5 MB
JS heap0.7 MB
Try it yourself
6,018 elements, 12,041 DOM nodes

This is Ravi's page from lessons 31.1 and 31.2. Pick another size to compare.

Recorded in Chrome 157 with the CPU 4 times slower. Each change is the middle of 9. The heaps and counts were read after a garbage collection, at the end of a load.

Let Chrome skip the reviews nobody can see

Lesson 28.2 met content-visibility on a long list of teas. Lesson 30.3 showed how it can make a page jump. Here it is on Ravi's reviews: what it saves, and what it costs. Ravi adds one rule:

Skip the reviews far from the screenCSS
.review {  content-visibility: auto;  contain-intrinsic-size: auto 190px;}
  • Line 1 picks every review.
  • Line 2 lets Chrome skip a review's insides while it's far from the screen. Chrome still lays out the review's own box, so the page keeps its length.
  • Line 3 gives a skipped review a size: a guess of 190 px for its insides. Ravi's reviews average 182.3 px inside, without their padding and border. auto keeps a review's real size once Chrome has drawn it, as lesson 30.3 showed.
Real-life analogyA hotel that makes up only the rooms near its guests

A hotel has 1,000 rooms. Each morning, the staff make up only the rooms near the guests. The other rooms stay shut, but the floor plan still shows every one, at its usual size. If a guest asks for room 900, the staff make it up and take them there.

In real life: The 1,000 rooms
In JavaScript: The 1,000 reviews, all still in the page
In real life: Rooms near the guests, made up
In JavaScript: Reviews near the screen, drawn
In real life: Shut rooms, at their usual size on the floor plan
In JavaScript: Skipped reviews: boxes of the guessed size
In real life: A guest who asks for room 900
In JavaScript: A link to #review-900, or find-in-page

Here is the load, with and without the rule:

The load, drawing every review or skippingPop out in the code editor (opens in a new tab)JavaScript
// Asha opens each page. Middle of 5 loads each.const loads = [  { page: "Every review drawn", firstFrame: 217.6, styled: 6015, layoutObjects: 12017, layoutMs: 97.8 },  { page: "Off-screen reviews skipped", firstFrame: 135.2, styled: 1068, layoutObjects: 1115, layoutMs: 29.3 },];for (const l of loads) {  console.log(`${l.page}: first frame ${l.firstFrame} ms, ${l.styled} elements styled, ${l.layoutObjects} layout objects in ${l.layoutMs} ms`);}
  • Lines 3 and 4 hold each page's middle load: the first frame, the elements styled, and the layout objects with their time.
  • Line 7 prints Every review drawn: first frame 217.6 ms, 6015 elements styled, 12017 layout objects in 97.8 ms.
  • Then it prints Off-screen reviews skipped: first frame 135.2 ms, 1068 elements styled, 1115 layout objects in 29.3 ms.
Ravi's page loading, to scale, until the first frame. Every review drawn: layout 97.8 ms for 12,017 layout objects, first frame at 217.6 ms. content-visibility: auto on each review: layout 29.3 ms for 1,115 layout objects, first frame at 135.2 ms.Every review drawn: 12,017 layout objects217.6 mscontent-visibility: auto on each review: 1,115 layout objects135.2 msAsha opens the page, 0 msEach row ends at its first frame.
The main thread until Asha's first frame, to scale. Each bar is a stretch of work; the shaded parts are Layout. With content-visibility, Chrome laid out far fewer boxes, and the reviews appeared sooner.

With the rule, Chrome styled 1,068 elements instead of 6,015. It laid out 1,115 objects instead of 12,017. The first frame came 82.4 ms sooner. Yet the page was the same: all 6,018 elements were still in it.

Look inside the second row to see how. Chrome's first layout skipped every review: 1,016 layout objects. Then Chrome checked which reviews were near the screen. It drew those in a second round, before the first frame, just as lesson 28.2 found.

Memory dropped too. Blink's heap was 4.6 MB instead of 11.5 MB, though all 12,041 DOM nodes were still there. Chrome built no styles and no layout objects for a skipped review's insides.

Not every change gets cheaper

The course made the two changes again, on the skipping page:

Two changes, drawing every review or skippingPop out in the code editor (opens in a new tab)JavaScript
// Two changes on the skipping page. Middle of 9 each.const changes = [  { change: "Narrower column", everyReview: 35.4, skipping: 3.7 },  { change: "Night reading", everyReview: 24.5, skipping: 67.2 },];for (const c of changes) {  console.log(`${c.change}: ${c.everyReview} ms drawing every review, ${c.skipping} ms skipping`);}
  • Lines 3 and 4 hold each change's middle time on both pages.
  • Line 7 prints Narrower column: 35.4 ms drawing every review, 3.7 ms skipping and Night reading: 24.5 ms drawing every review, 67.2 ms skipping.

A narrower column changes every review's width. Chrome laid out each skipped review's box, and nothing inside it. Night reading changes the colours of every review's card. So Chrome still restyled all 1,000 cards, and on this page that took longer than before. The trace doesn't show where the extra time went.

Why it matters: content-visibility doesn't make every change cheaper. Time your own changes, with and without it.

The work waits for the scroll

Skipped work isn't gone. It waits until Asha scrolls. The course scrolled each page down one screen at a time, eight times:

  • Every review drawn: 1.1 to 2 ms of rendering work per screen. Chrome had laid everything out at load, so it mostly painted.
  • content-visibility: 9.6 to 15.1 ms per screen. Chrome checked which reviews had come near, then styled, laid out and painted them. The checks alone took 3.8 to 5.7 ms each time.

Chrome draws a review once it's within 150% of the screen's height, as lesson 28.2 found. So the work happens before the review comes into view. Why it matters: content-visibility moves work from the load to the scroll. That's a good deal when most reviews are never reached.

What still works: links, Tab, find-in-page and screen readers

The CSS Containment spec says skipped content "must still be available as normal" to find-in-page and tab order. The course checked on Ravi's page:

  • A link to a review. Jumping to #review-900 put review 900 at the top of the screen, just as on the page that draws every review.
  • Tab. From review 7's Helpful button, Tab went to review 8's, on both pages.
  • Find-in-page. It found Marrakesh, a word only review 900 has. It also cost a lot, as you'll see next.

Chrome's find-in-page doesn't search skipped reviews as they are. Its source first forces every skipped review to be styled and laid out, then searches. window.find() does the same, so the course timed that:

One search, on both pagesPop out in the code editor (opens in a new tab)JavaScript
// Searching for "Marrakesh", a word only review 900 hasconst searches = [  { page: "Every review drawn", found: true, ms: 39.8 },  { page: "Off-screen reviews skipped", found: true, ms: 240.4 },];for (const s of searches) {  console.log(`${s.page}: found ${s.found}, in ${s.ms} ms`);}
  • Lines 3 and 4 hold each page's search for the word in review 900: whether it was found, and how long it took.
  • Line 7 prints Every review drawn: found true, in 39.8 ms and Off-screen reviews skipped: found true, in 240.4 ms.

Before it could search, Chrome styled 5,948 elements and laid out 11,904 objects. After the search and a clean-up, Blink's heap was 13.4 MB, not 4.6 MB. Why it matters: one search can undo the savings.

Screen readers read the accessibility tree: a version of the page that Chrome builds for them, with every heading, list item and button. The spec says a browser mustn't undo the skipping just to build that tree. If it can't avoid it, it must leave the skipped content out. Chrome's source says when it leaves it out: "When screen readers are not present, it is safe to prune display-locked content". Display-locked is Blink's word for skipped.

The course read the tree twice. With no screen reader, it held all 1,000 list items but only 10 headings: the page's title and the drawn reviews' names. Then the course started Chrome in screen reader mode. All 1,001 headings were there, and so was Marrakesh. To build them, Chrome styled 6,024 elements during the load. It still laid out only 1,115 objects.

Why it matters: content-visibility keeps the page readable with a screen reader. For those visitors, it saves the layout but not the styles.

Make the column narrower in your own browser:

Playground: skip the reviews in your browser
The page's extra ruleCSS
/* No extra rule: every review is drawn */
Every review drawnNarrower column
Layout, in Chrome35.4 ms
Layout, in your browsernot timed yet
Try it yourself
Every review is laid out again

A narrower column changes every review's width, so Chrome breaks every line of every review again.

"Time it" loads Ravi's 1,000-review page below and makes its column narrower 3 times, timing the layout each time. The Chrome number is the course's recording, with the CPU slowed. Your number depends on your computer.

Containment: the promise that lets Chrome skip

How can Chrome skip a review safely? Lesson 31.2 met the contain property: a promise that a box is cut off from the rest of the page. content-visibility is built on it. The spec has four kinds of containment:

  • Size: the box is sized as if it were empty. Its contents can't change its size.
  • Layout: nothing inside affects the layout outside, and the other way round.
  • Paint: nothing inside is drawn outside the box. So if the box is off the screen, so is everything in it.
  • Style: a few styles, like CSS counters, can't reach outside the box.

content-visibility: auto turns on layout, paint and style containment for each review. While a review is skipped, it adds size containment too. So a skipped review can't move anything around it, can't draw outside its box, and has a fixed size: the guess. Chrome can lay out the page without looking inside.

Real-life analogyFlats with solid walls

A block of flats has solid walls. A family can move furniture or repaint, and the walls next door don't move. Each flat's size is on the building plan. So the caretaker can check the whole block without opening a single door.

In real life: Each flat
In JavaScript: Each review with containment
In real life: Walls that never move
In JavaScript: Layout containment
In real life: Nothing seen outside the flat
In JavaScript: Paint containment
In real life: The flat's size on the building plan
In JavaScript: Size containment, with its guessed size
In real life: Checking the block without opening a door
In JavaScript: Laying out the page without a skipped review's insides

But the promise isn't the skipping. Ravi tried the promise alone, on every review:

Containment, without content-visibilityCSS
.review { contain: content; }

Line 1 turns on layout, paint and style containment for every review. The load's layout still took 106 ms for 12,017 objects. The narrower column took 32.2 ms, against 35.4 ms. Blink's heap was 12.8 MB, a little more than without it.

Containment told Chrome that the reviews were cut off from each other. It didn't tell Chrome to skip them. content-visibility does both.

Inside Blink: a lock on each review

In Blink's source, a skipped element has a display lock. Before each step, Blink asks the lock four questions: should it style the children, lay them out, pre-paint them, paint them? While the lock is on, all four answers are no, unless something forces them, like find-in-page. The element itself is still styled and laid out, as a box of the guessed size.

The lock comes off in two ways:

  • The review comes near the screen. Chrome checks this with its own intersection observer, with the 150% margin.
  • Something needs what's inside: find-in-page, a link to it, focus moving into it, scrollIntoView(), or a selection. For a link or find-in-page, Blink keeps the lock off for two frames, so the scroll can land.

content-visibility: hidden keeps the work

content-visibility has a third value, hidden. It skips an element's insides always, near the screen or not. The spec hides them from find-in-page and tab order too, like display: none. Ravi tries it on a new Hide reviews switch:

Two ways to hide the listCSS
/* Version 1 */#reviews.hidden { display: none; }/* Version 2 */#reviews.hidden { content-visibility: hidden; }
  • Line 2 is version 1: the hidden list gets display: none.
  • Line 4 is version 2: content-visibility: hidden.
Showing the list againPop out in the code editor (opens in a new tab)JavaScript
// Asha turns Hide reviews off, and the list comes back. Middle of 9.const versions = [  { hiddenWith: "display: none", styled: 6004, layoutObjects: 12006, ms: 89.7 },  { hiddenWith: "content-visibility: hidden", styled: 3, layoutObjects: 5, ms: 4.4 },];for (const v of versions) {  console.log(`${v.hiddenWith}: ${v.styled} elements styled, ${v.layoutObjects} layout objects, ${v.ms} ms`);}
  • Lines 3 and 4 hold each version's middle time to show the list again, and what Chrome redid.
  • Line 7 prints display: none: 6004 elements styled, 12006 layout objects, 89.7 ms and content-visibility: hidden: 3 elements styled, 5 layout objects, 4.4 ms.

Both hide the list. But display: none throws away its styles and layout objects. web.dev says showing it again is "as expensive as rendering a new element with the same contents". content-visibility: hidden kept them, so showing the list redid almost nothing.

Real-life analogyA stage set kept in the wings

A theatre swaps between two plays. One crew takes the first play's set apart after each show, and builds it again the next night. Another crew rolls the built set into the wings, and rolls it back on when it's needed.

In real life: Taking the set apart after the show
In JavaScript: display: none: styles and layout objects thrown away
In real life: Building it again for the next show
In JavaScript: Styling 6,004 elements and laying out 12,006 objects
In real life: Rolling the built set into the wings
In JavaScript: content-visibility: hidden: the work is kept
In real life: Rolling it back on
In JavaScript: Showing the list in 4.4 ms

hidden="until-found": hidden, but findable

HTML has a cousin of this. The hidden attribute with the value until-found hides an element with content-visibility: hidden, not display: none. The HTML spec says its content stays "accessible to find-in-page and fragment navigation". Fragment navigation means following a link to an id, like #review-900. When either one needs the content, the browser shows it first. That suits Ravi's long reviews:

The end of review 900, hidden until foundHTML
<p class="review-text">We drank it on a night train to Marrakesh, and it was perfect.</p><p class="review-text" id="more-900" hidden="until-found">The man in the next seat asked where I bought it, so I wrote down Leaf and Kettle for him.</p>
  • Line 1 is the start of review 900's words.
  • Line 2 is the rest of them, hidden until found.

The course jumped to #more-900. Chrome fired a beforematch event at the paragraph, took its hidden attribute off, and scrolled the words to the top of the screen. A script can listen for that event, to update a Read more button.

Keep only the nearby reviews in the page

content-visibility keeps every review in the page. The other way is to leave most of them out. A virtual list keeps the reviews as data, and puts only the ones near the screen in the page. Lessons 28.2 and 28.3 used one on a list of teas. The system design lesson List virtualization shows how libraries build them. Here is Ravi's, shortened to its core:

Ravi's virtual listJavaScript
// Only the reviews near the screen are in the pageconst list = document.querySelector("#reviews");const sizes = reviews.map(() => 230);function draw() {  for (const item of list.children) sizes[item.dataset.i] = item.offsetHeight + 12;  const top = -list.getBoundingClientRect().top - 800;  const bottom = top + innerHeight + 1600;  let first = 0, y = 0;  while (first < reviews.length - 1 && y + sizes[first] < top) y += sizes[first++];  let last = first, end = y;  while (last < reviews.length && end < bottom) end += sizes[last++];  list.style.paddingTop = `${y}px`;  list.style.paddingBottom = `${sizes.slice(last).reduce((a, b) => a + b, 0)}px`;  list.innerHTML = reviews.slice(first, last).map(reviewHtml).join("");}addEventListener("scroll", draw, { passive: true });draw();
  • Line 2 finds the list. Line 3 gives every review a guessed size: 230 px, for a review and the 12 px gap above it.
  • Line 5 reads the real height of each review in the page, and keeps it.
  • Lines 6 and 7 work out which part of the list to fill: the screen, and 800 px above and below it.
  • Lines 8 to 11 walk through the sizes to find the first and the last review in that part.
  • Lines 12 and 13 pad the list above and below, so it's as tall as all 1,000 reviews would be.
  • Line 14 puts only those reviews in the page. reviewHtml builds one review's HTML.
  • Lines 16 and 17 draw again on every scroll, and once at the start.

Its reads, on lines 5 and 6, come before its writes, on lines 12 to 14, as lesson 31.2 taught.

Real-life analogyA library that shelves only the books near you

Picture a library where a librarian walks with you. Only the shelves around you hold books. As you walk, she shelves the books ahead and takes away the ones behind. It saves a lot of shelf space. But you can't scan a shelf you haven't reached, and the catalogue can't send you to a book that isn't out.

In real life: Books in boxes at the back
In JavaScript: The 1,000 reviews, kept as data
In real life: The shelves around you
In JavaScript: The reviews in the page, near the screen
In real life: The librarian shelving as you walk
In JavaScript: draw(), on every scroll
In real life: A book that isn't on a shelf
In JavaScript: A review that isn't in the page

Here is what the virtual list cost when Asha opened the page:

  • 7 reviews in the page: 62 elements and 125 DOM nodes.
  • A layout of 100 objects, and the first frame at 90.2 ms.
  • Blink's heap: 0.46 MB. The JS heap grew by about 47 KB, for the reviews' data.
Three ways to have Ravi's 1,000 reviews, each shown as the top of the page. Every review drawn: every review is in the page and drawn, 6,018 elements. content-visibility: auto: every review is in the page, 6,018 elements, but only the reviews near Asha's screen are drawn; the others are empty boxes of a guessed size. A virtual list: only the reviews near the screen are in the page at all, 62 elements.Every review drawnAshaRaviMeeraBenAnaSamPriyaLeo6,018 elements12,017 layout objectsfirst frame 217.6 mscontent-visibility: autoAshaRaviMeeraBenAnaSamskippedskipped6,018 elements1,115 layout objectsfirst frame 135.2 msA virtual listAshaRaviMeeraBenAnaSamnot in the page62 elements100 layout objectsfirst frame 90.2 msAsha's screen
The top of each page. The dashed line beside each column spans Asha's screen. Shaded cards are drawn. Dashed cards are in the page but skipped. In the virtual list, the far reviews aren't in the page at all.

Scrolling cost 2.9 to 7.8 ms per screen, between the other two pages. Each time, Ravi's script ran, and Chrome styled and laid out the new reviews. Step through every screen of all three pages:

Playground: scroll down one screen
Each scrollJavaScript
// Screen 1: scroll down one screen
window.scrollBy(0, innerHeight);
Every review drawnScreen 1
Reviews in the page1,000
Chrome's checks for content-visibility0 ms
Ravi's script0.008 ms
Recalculate style0 ms
Layout0 ms
Pre-paint and paint1.8 ms
Try it yourself
1.8 ms of rendering work

Every review was laid out at load, so scrolling only paints what's newly on screen.

Recorded in Chrome 157 with the CPU 4 times slower. The course scrolled each page down one screen at a time, 8 times, and added up the main thread's work after each scroll.

What a virtual list breaks

A review that isn't in the page isn't anywhere for the browser. The course checked the same things as before:

  • Find-in-page. window.find("Marrakesh") returned false. Review 900 wasn't in the page.
  • Links. Jumping to #review-900 did nothing. The page stayed at the top.
  • Tab. From review 7's Helpful button, the last one in the page, Tab left the reviews. Review 8 wasn't there yet.
  • Screen readers. In screen reader mode, the tree held 7 list items, and none of the other 993.
  • The scrollbar. From its guesses, the page started 230,182 px tall. With every review drawn, it's 222,475 px.

Each one has a fix, and each fix is more code. A search box can search the data. A "go to review" button can scroll by number. ARIA attributes can tell a screen reader each review's place in the full list: exercise 6 asks which. The system design lesson has a flowchart for choosing.

Why it matters: the virtual list was the cheapest page here. It's also the one that needs the most care.

Which way fits Ravi's page?

Here is every way the course drew Ravi's 1,000 reviews. Read each row across: the elements in the page, the layout objects at load, the narrower column's layout, and Blink's heap.

1,000 reviews, four ways
How the reviews are drawnElements in the pageLayout objects at loadNarrower columnBlink heap
Every review drawn6,01812,01735.4 ms11.5 MB
contain: content on each review6,01812,01732.2 ms12.8 MB
content-visibility: auto on each review6,0181,1153.7 ms4.6 MB
A virtual list621000.59 ms0.5 MB

Now sort some pages. Ask: does the visitor need to reach every item with find, links and Tab? How many items are there? Is a part hidden for a while?

Which way fits?
  • A product page with 12 teas
  • A long brewing guide in 40 sections that readers search with Ctrl+F
  • 1,000 reviews, where each review can be linked to
  • A chat history of 200,000 messages
  • A spreadsheet with 100,000 rows
  • A Reviews tab that Asha switches away from and back to
  • Long answers folded shut, which find-in-page should still open
Try it yourself
0 of 7 correct

Sort each page by the way to draw it.

Choose a category for every card. You can change an answer at any time; Reset clears them all.

Common mix-ups

  • "Elements off the screen cost nothing." No. Chrome styled and laid out all 1,000 reviews before showing three.
  • "A big DOM shows up in the JS heap." No. The JS heap stayed at 0.72 MB. The DOM's memory is in Blink's heap: 11.5 MB for 1,000 reviews.
  • "contain: content on each review skips work." No. The load still laid out 12,017 objects. content-visibility adds the skipping.
  • "content-visibility makes every change cheaper." No. Night reading took 67.2 ms with it, and 24.5 ms without.
  • "Ctrl+F can't find skipped content." No. Chrome found the word in review 900, after styling and laying out every skipped review.
  • "A virtual list has no downsides." No. Find, the link to review 900 and Tab all failed on it.

Practice exercises

Answer first, then use the hints.

Exercise 1 · Warm-upCount the elements

Ravi's page has 6 elements per review, and 18 for everything else. What does this print for 2,000 reviews?

Starter codePop out in the code editor (opens in a new tab)JavaScript
// Ravi's page: 6 elements per review, and 18 for the rest
const perReview = 6;
const rest = 18;
const reviews = 2000;
console.log(perReview * reviews + rest);

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · Warm-upHow far ahead Chrome draws

    Asha's screen is 823 px tall. What does this print?

    Starter codePop out in the code editor (opens in a new tab)JavaScript
    // Chrome draws a skipped review once it's within 150% of the screen's height
    const screenHeight = 823;
    const margin = 1.5;
    console.log(`Reviews up to ${screenHeight * margin} px below the screen are drawn.`);

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeSkip the right thing

      Ravi puts the rule on the whole list. It skips nothing. Which selector should it use instead?

      Starter codeCSS
      #reviews {
        content-visibility: auto;
        contain-intrinsic-size: auto 190px;
      }

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · PracticeDrawn while scrolling

        In the scrolling playground, pick content-visibility: auto and Screen 4. How many reviews were drawn?

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeThe insight's DOM depth

          Download the course's trace of the 1,000-review page loading. Load it in DevTools' Performance panel, and open the Optimize DOM size insight. What DOM depth does it report?

          Answer, then press Check. Spacing and letter case don’t matter.

            Exercise 6 · ChallengeTell a screen reader the real size

            Ravi's virtual list has only a few reviews in the page. Which ARIA attribute, on each review, tells a screen reader the list really holds 1,000?

            Answer, then press Check. Spacing and letter case don’t matter.

              Check your understanding

              For each question, ask: is the review in the page, is it drawn, and what did Chrome have to redo?

              The DOM size quiz · 7 questionsScore: first tries count
              1. Question 1 of 7Ravi's page had 1,000 reviews, and Asha's screen showed three. What did Chrome do with the other 997 before her first frame?

                Choose an answer to see the explanation.

              2. Question 2 of 7What does this division of two recorded Blink heaps print?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                const blinkHeapMB = { reviews1000: 11.5, reviews5000: 56.2 };
                console.log((blinkHeapMB.reviews5000 / blinkHeapMB.reviews1000).toFixed(1));

                Choose an answer to see the explanation.

              3. Question 3 of 7Ravi put contain: content on every review. What did it save when the page loaded?

                Choose an answer to see the explanation.

              4. Question 4 of 7On the page with content-visibility: auto, Asha searches with Ctrl+F for a word in review 900. What happens?

                Choose an answer to see the explanation.

              5. Question 5 of 7Why did the list come back faster when Ravi hid it with content-visibility: hidden instead of display: none?

                Choose an answer to see the explanation.

              6. Question 6 of 7What did the virtual list lose that content-visibility: auto kept?

                Choose an answer to see the explanation.

              7. Question 7 of 7Without a screen reader running, what does Chrome put in the accessibility tree for a skipped review?

                Choose an answer to see the explanation.

              Key takeaways

              • Chrome styles, lays out and keeps in memory every element in the page, on screen or not. Five times the reviews cost about five times as much.
              • Count elements in the console, watch DOM nodes in DevTools, and read the Optimize DOM size insight. It fails only on big, slow steps.
              • content-visibility: auto skips the insides of far-away elements. Ravi's load laid out 1,115 objects instead of 12,017. The work moves to the scroll.
              • Links, Tab and find-in-page still reach skipped content. Find renders all of it first. With a screen reader running, Chrome styles it too.
              • Containment is the promise; content-visibility adds the skipping. content-visibility: hidden keeps the work a hidden part has done.
              • A virtual list keeps the fewest elements, and breaks find, links, Tab and screen readers unless you add them back.

              Remember the one-liner.
              Every element costs work, seen or not: let Chrome skip what's far away, or leave it out of the page.

              Sources

              The facts on this page come from these specs, docs and source files:

              Coming next: Paint and layers. After style and layout comes paint. You'll see what makes a paint slow, and when a layer of its own helps.

              CompleteFrontend Clear concepts. Working examples.