JavaScriptAdvanced

JavaScript Browser Performance: Reflow, Repaint and Layout

Learn browser performance in JavaScript: reflow, repaint, layout thrashing, batching DOM updates, requestAnimationFrame, lazy loading and how to measure speed.

All JavaScript lessons (83)View curriculum

What you will learn

You can write JavaScript that is correct and still feels slow: a menu that opens with a delay, a list that freezes the page for a second, an animation that stutters. Most of the time the slowness is not in your calculations. It is in how your code talks to the browser, in particular how often it makes the browser recalculate the layout and redraw the screen.

In this lesson you will learn how the browser turns your page into pixels, what reflow and repaint are, how layout thrashing quietly slows down code that looks innocent, how to batch DOM operations, how to use requestAnimationFrame() for smooth animations and scroll handlers, how to lazy load things you do not need yet, and how to measure performance instead of guessing. This lesson continues the debounce and throttle lesson, and the CSS side of the same story is in the CSS performance lesson.

The idea in one line

The browser can draw a new picture about 60 times per second, so each frame has roughly 16 milliseconds. Your JavaScript, the layout work and the painting must all fit inside that time.

Think of a restaurant kitchen. Orders arrive (your JavaScript), the chef cooks (layout: working out sizes and positions), the plates are decorated (paint), and the waiter serves them (composite). If you keep changing the order in the middle of cooking, the chef must start again each time. If you send 500 orders one by one, with a question after each, the kitchen never gets into a rhythm. Good performance means sending your changes in neat, well-timed batches.

How the browser draws a page

After the HTML and CSS are loaded, every time something changes the browser goes through these steps:

Step What happens Name you will hear
1. JavaScript Your code runs and changes the DOM or styles (your code)
2. Style Work out which CSS rules apply to which element Recalculate style
3. Layout Work out the size and position of every box Reflow
4. Paint Fill in the pixels: colours, text, borders, shadows Repaint
5. Composite Put the painted layers together on the screen Composite

Everything above happens on the main thread, the single thread that also runs your JavaScript and handles clicks (the event loop lesson explained why there is only one). While one step runs, the others wait. If your JavaScript takes 200 ms, the page cannot paint or answer a click for 200 ms. It looks frozen.

The more steps a change triggers, the more expensive it is.

Reflow and repaint

  • A reflow (also called layout) happens when something changes the geometry: width, height, position, font size, adding or removing elements. The browser must recalculate positions, and a change in one box can push many other boxes around. This is the most expensive step.
  • A repaint happens when something changes only the look: colour, background, shadow, visibility. The positions stay the same, so layout is skipped, but pixels must be redrawn.
  • Composite-only changes are the cheapest: transform and opacity can be handled by the graphics card without redoing layout or paint.
What you change Layout Paint Composite
width, height, margin, padding, top, left, font-size, adding or removing elements yes yes yes
color, background-color, box-shadow, border-color, visibility no yes yes
transform, opacity no no yes

This is the same table that the CSS performance lesson showed. Now see it from JavaScript. These two do the same visible job (move a box 200 px to the right), but they cost very different amounts:

const box = document.querySelector(".box");

// Expensive: changes layout on every step
box.style.left = "200px";

// Cheap: only the compositor moves it
box.style.transform = "translateX(200px)";

Rule of thumb: to move, scale or fade something, animate transform and opacity, not left, top, width or height.

Forced layout and layout thrashing

Here is a secret that makes code faster by default. When you change the DOM, the browser does not recalculate the layout immediately. It waits, collects all your changes, and recalculates once, just before drawing the next frame. Changes are lazy and batched. Great!

But some things you can read need an up-to-date layout. For example, “How wide is this element?” If you ask while there are unprocessed changes, the browser has no choice: it must stop and recalculate the layout right now, just to answer you. This is called a forced synchronous layout (or forced reflow).

Properties and methods that force a layout when the layout is dirty include:

  • element.offsetWidth, offsetHeight, offsetTop, offsetLeft
  • element.clientWidth, clientHeight (you met clientWidth in the BOM lesson)
  • element.getBoundingClientRect()
  • getComputedStyle(element) values such as width
  • window.innerWidth, window.innerHeight, window.scrollY

One forced layout is fine. The trouble starts when you mix reads and writes in a loop. Every write makes the layout dirty, and the next read forces a recalculation. Repeating this for hundreds of elements is called layout thrashing.

const cards = document.querySelectorAll(".card");

// BAD: read, write, read, write... (a forced layout on every single loop)
for (const card of cards) {
  const width = card.offsetWidth;            // READ  : forces layout (it is dirty from the last write)
  card.style.width = (width + 10) + "px";    // WRITE : makes the layout dirty again
}

Imagine 400 cards. The browser recalculates the whole layout 400 times instead of once.

The fix: read everything first, then write everything

const cards = [...document.querySelectorAll(".card")];

// GOOD: all reads first
const widths = cards.map((card) => card.offsetWidth);     // one layout at most

// then all writes
cards.forEach((card, i) => {
  card.style.width = (widths[i] + 10) + "px";             // changes are collected...
});
// ...and the browser recalculates the layout ONCE, before the next frame

The rule is simple: never alternate. Group your work into a read phase and a write phase.

Pattern Layouts calculated
Read, write, read, write (400 times) up to 400
400 reads, then 400 writes about 1

Try the Practice Editor below the lesson: the two buttons run exactly these two versions and show the time each takes. (The numbers depend on your computer. The batched version is usually clearly faster, and the difference grows with the number of elements.)

Another classic: equal-height cards

“Make every card as tall as the tallest one” is the usual place where thrashing appears. The right way:

function equalizeHeights(cards) {
  cards.forEach((card) => { card.style.height = ""; });          // 1. reset (write)

  const heights = cards.map((card) => card.offsetHeight);        // 2. read all
  const tallest = Math.max(...heights);

  cards.forEach((card) => { card.style.height = tallest + "px"; });   // 3. write all
}

(Today, CSS Grid and Flexbox do this for you without JavaScript, so use CSS when you can.)

Batching DOM operations

Every change to the live page has a cost. Do as much work as possible away from the page, and touch the page once.

1. Build first, insert once (DocumentFragment)

You learned this in the creating and removing elements lesson. Here is the same idea in the performance picture:

const list = document.getElementById("list");
const items = Array.from({ length: 2000 }, (_, i) => "Item " + (i + 1));

// SLOWER: 2000 separate insertions into the live page
items.forEach((text) => {
  const li = document.createElement("li");
  li.textContent = text;
  list.append(li);
});

// FASTER: build in memory, insert once
const fragment = document.createDocumentFragment();

items.forEach((text) => {
  const li = document.createElement("li");
  li.textContent = text;
  fragment.append(li);
});

list.append(fragment);              // one insertion, one layout

list.replaceChildren(...newItems) replaces everything in one step, too.

2. Do not use innerHTML += in a loop

// BAD: rebuilds and re-parses ALL the existing content every time (and removes its event listeners)
for (const text of items) {
  list.innerHTML += "<li>" + text + "</li>";
}

// GOOD: build one string (or use a fragment), assign once
list.innerHTML = items.map((text) => "<li>" + text + "</li>").join("");

(If the text comes from users, prefer textContent or elements, so you do not create a security hole. See the DOM lessons.)

3. Change many styles at once with a class

// BAD: several separate style writes
box.style.width = "300px";
box.style.height = "200px";
box.style.background = "tomato";
box.style.borderRadius = "12px";

// GOOD: one class change, with the styling in CSS
box.classList.add("expanded");

4. Work on a hidden element

If you must change a lot of things inside one element, you can hide it first, change it, and show it again. A hidden element (display: none) does not take part in layout:

list.hidden = true;                  // out of the layout

// ...make many changes inside list...

list.hidden = false;                 // back in, one layout

5. Cache your lookups

// BAD: the same search is repeated 1000 times
for (let i = 0; i < 1000; i++) {
  document.querySelector("#total").textContent = i;
}

// GOOD: find it once
const total = document.querySelector("#total");
for (let i = 0; i < 1000; i++) {
  total.textContent = i;     // (and in real code you would only write the final value once)
}

6. Fewer listeners: use event delegation

A thousand rows with a thousand listeners cost memory and setup time. One listener on the parent can handle them all, as the event delegation lesson showed:

list.addEventListener("click", (event) => {
  const item = event.target.closest("li");
  if (item) console.log("Clicked", item.textContent);
});

requestAnimationFrame(): draw at the right moment

You met setTimeout and setInterval for animation in the timers lesson, which also said that requestAnimationFrame is better. Here is why.

A timer fires at its own moment, which has nothing to do with the screen. It may fire in the middle of a frame, or twice before the next one, so work is wasted or the motion looks uneven.

requestAnimationFrame(callback) says to the browser: “Run my function just before you draw the next frame.” The browser chooses the perfect moment, matched to the screen’s refresh rate (60 times per second on most screens, more on some).

function frame(timestamp) {
  console.log("A new frame is about to be drawn at", timestamp);
}

requestAnimationFrame(frame);       // runs once, before the next paint
  • The callback receives a timestamp in milliseconds (the same kind of clock as performance.now()).
  • It runs once. To keep animating, ask for the next frame inside the callback.
  • It pauses in background tabs, which saves battery and CPU.
  • cancelAnimationFrame(id) stops a request, exactly like clearTimeout.
let frameId = null;

function loop(timestamp) {
  // update something here
  frameId = requestAnimationFrame(loop);      // ask for the next frame
}

frameId = requestAnimationFrame(loop);        // start

cancelAnimationFrame(frameId);                // stop

Animate with time, not with frame counts

Do not move “5 pixels per frame”. A screen at 120 Hz would run twice as fast as one at 60 Hz. Instead, calculate the progress from the elapsed time:

function animate({ duration, onFrame, easing = (t) => t }) {
  return new Promise((resolve) => {
    let startTime = null;

    function frame(now) {
      if (startTime === null) startTime = now;

      const t = Math.min((now - startTime) / duration, 1);   // progress from 0 to 1
      onFrame(easing(t));

      if (t < 1) {
        requestAnimationFrame(frame);
      } else {
        resolve();                                           // finished
      }
    }

    requestAnimationFrame(frame);
  });
}

const easeOut = (t) => 1 - Math.pow(1 - t, 3);

const ball = document.getElementById("ball");

await animate({
  duration: 1000,
  easing: easeOut,
  onFrame: (t) => {
    ball.style.transform = "translateX(" + t * 300 + "px)";   // transform: cheap!
  }
});

console.log("Animation finished");

Because animate returns a Promise (see the Promises lesson), you can await it, and chain animations one after the other. easing makes the motion start fast and slow down at the end. (Remember: top-level await works inside a module, or inside an async function.)

Count up smoothly

function countUp(element, target, duration = 1200) {
  const start = Number(element.textContent) || 0;

  return animate({
    duration,
    easing: (t) => 1 - Math.pow(1 - t, 3),
    onFrame: (t) => {
      element.textContent = Math.round(start + (target - start) * t);
    }
  });
}

countUp(document.getElementById("visitors"), 12840);

A perfect scheduler for scroll and resize

In the debounce and throttle lesson you limited scroll handlers with a timer. There is an even better rhythm: at most once per frame, because drawing more often than the screen refreshes is useless. Here is a rafThrottle:

function rafThrottle(fn) {
  let frameId = null;
  let lastArgs;

  function throttled(...args) {
    lastArgs = args;                          // always remember the newest values

    if (frameId !== null) return;             // a frame is already scheduled

    frameId = requestAnimationFrame(() => {
      frameId = null;
      fn(...lastArgs);                        // runs once per frame, with the latest values
    });
  }

  throttled.cancel = () => {
    cancelAnimationFrame(frameId);
    frameId = null;
  };

  return throttled;
}

const updateHeader = rafThrottle(() => {
  header.classList.toggle("small", window.scrollY > 80);
});

window.addEventListener("scroll", updateHeader, { passive: true });

No matter how many scroll events arrive, the handler runs at most once per frame, and always with the latest values.

Use rAF to separate reads and writes

requestAnimationFrame is also a convenient place for writes. A common pattern: read in the event handler, write in the next frame:

window.addEventListener("scroll", () => {
  const scrollY = window.scrollY;               // read now

  requestAnimationFrame(() => {
    progress.style.transform = "scaleX(" + Math.min(scrollY / 2000, 1) + ")";   // write in the frame
  });
}, { passive: true });

CSS or JavaScript for animation?

Use CSS (transition, @keyframes) when Use JavaScript + rAF when
The animation is fixed: hover, open and close, fade The values depend on data or user input (drag, scroll position, game logic)
You only need transform and opacity You must draw on a <canvas> or control every frame
You want the browser to optimise it for you You need to chain, pause, or react to progress in code

CSS animations are very well optimised, so reach for them first, as the CSS animation lessons showed.

Do not block the main thread: split long tasks

Imagine you must show 5000 rows, or process a big array. If one function does all the work in one go, the page is blocked until it ends: no clicks, no scrolling, no animation (the event loop lesson explained why). Any single piece of work longer than about 50 ms is called a long task and is felt by the user.

The solution: split the work into small chunks, and give the browser a chance to paint and respond between the chunks.

const nextFrame = () => new Promise((resolve) => requestAnimationFrame(resolve));

async function renderInChunks(items, renderChunk, chunkSize = 200, onProgress = () => {}) {
  for (let i = 0; i < items.length; i += chunkSize) {
    renderChunk(items.slice(i, i + chunkSize));       // a small piece of work

    onProgress(Math.min(i + chunkSize, items.length) / items.length);

    await nextFrame();                                // let the browser paint and handle clicks
  }
}

const rows = Array.from({ length: 5000 }, (_, i) => "Row " + (i + 1));
const list = document.getElementById("list");

await renderInChunks(
  rows,
  (chunk) => {
    const fragment = document.createDocumentFragment();

    for (const text of chunk) {
      const li = document.createElement("li");
      li.textContent = text;
      fragment.append(li);
    }

    list.append(fragment);
  },
  250,
  (progress) => console.log(Math.round(progress * 100) + "%")
);

The user sees the first rows right away, the page stays responsive, and a progress bar can be shown.

For work that has no screen output (for example, adding up numbers), you can yield with a timer instead:

const yieldToMain = () => new Promise((resolve) => setTimeout(resolve, 0));

async function sumBig(limit) {
  let total = 0;

  for (let i = 0; i < limit; i++) {
    total += i;

    if (i % 250000 === 0) {
      await yieldToMain();         // a macrotask: the browser can paint and handle events
    }
  }

  return total;
}

Important: await on an already resolved Promise only waits for a microtask, and the browser cannot paint between microtasks (see the microtasks lesson). To truly give the browser a break, wait for a macrotask (setTimeout) or the next frame (requestAnimationFrame), as above.

For really heavy calculations, even chunking is not enough. The next lesson shows Web Workers, which run work on a completely different thread.

Lazy loading: do not load what is not needed yet

The fastest code is the code that never runs, and the fastest download is the one you never start. Lazy loading means loading things only when they are needed.

1. Images and iframes: the loading attribute

You learned this in the HTML images lesson. One word gives you lazy loading, with no JavaScript:

<img src="photo.jpg" alt="A mountain" width="800" height="600" loading="lazy">
<iframe src="https://example.com/video" title="Video" loading="lazy"></iframe>

The browser downloads the image only when it is near the screen. Always give images a width and height (or CSS aspect-ratio), so that the page does not jump when they arrive. The jump is a layout shift, and the CSS performance lesson showed how to prevent it. Do not lazy load the main image at the top of the page, the one the user sees first.

2. Scripts: defer and dynamic import()

Load scripts with defer (HTML document structure lesson) so they do not block the page. And load heavy features only when they are used, with the dynamic import() from the modules lesson:

const exportButton = document.getElementById("exportBtn");

exportButton.addEventListener("click", async () => {
  exportButton.disabled = true;

  const { exportToPdf } = await import("./features/exportPdf.js");   // downloaded only now
  await exportToPdf(data);

  exportButton.disabled = false;
});

3. Lazy values: compute on first use

const report = {
  get summary() {
    console.log("Calculating (only the first time)...");
    const result = expensiveCalculation();

    Object.defineProperty(this, "summary", { value: result });   // replace the getter with the value
    return result;
  }
};

(You built this pattern in the property descriptors lesson.)

4. Long pages and lists

  • content-visibility: auto in CSS lets the browser skip the layout and painting of sections that are off-screen (CSS performance lesson).
  • For lists with tens of thousands of rows, virtualization shows only the rows that are visible (plus a few extra), and creates and recycles those few elements as the user scrolls. Libraries do this for you.
  • To detect “this element is now visible” efficiently, there is a dedicated tool, the Intersection Observer, which has its own lesson soon. It replaces the old trick of measuring positions in a scroll listener, which was a common cause of layout thrashing.

Measure first, then optimize

“Premature optimization is the root of all evil.” Do not guess where the slowness is. Measure. Most code is already fast enough, and a lot of “optimizations” make the code harder to read for no gain.

1. console.time (a quick check)

You used it in the debugging lesson:

console.time("render");
renderList();
console.timeEnd("render");     // render: 12.4 ms (your time will differ)

2. performance.now() (precise numbers you can use in code)

performance.now() returns the number of milliseconds since the page started, with a fraction for high precision. Take the time before and after:

const start = performance.now();

doSomething();

const elapsed = performance.now() - start;
console.log("Took " + elapsed.toFixed(2) + " ms");

A single run is not reliable. The first run is often slower (the engine is still “warming up”), and other things on the computer add noise. Run several times and look at the middle value (median):

function measure(label, fn, runs = 7) {
  const times = [];

  for (let i = 0; i < runs; i++) {
    const start = performance.now();
    fn();
    times.push(performance.now() - start);
  }

  times.sort((a, b) => a - b);
  const median = times[Math.floor(times.length / 2)];

  console.log(label + ": median " + median.toFixed(2) + " ms (min " + times[0].toFixed(2) + ", max " + times.at(-1).toFixed(2) + ")");
  return median;
}

measure("map + join", () => Array.from({ length: 100000 }, (_, i) => i * 2).join(",").length);

(There is a whole later lesson about the Performance API, with performance.mark and performance.measure, Navigation Timing and more. Here you only need performance.now().)

3. The DevTools Performance panel (see the real picture)

Open DevTools > Performance (see the debugging lesson):

  1. Click Record, use the page (scroll, click, type), and click Stop.
  2. Look at the Main thread. Each block is a piece of work, and the width is the time it took. Wide blocks are your suspects.
  3. Long tasks are marked with a red corner (longer than 50 ms). Click one to see which function was responsible.
  4. Look for the purple Recalculate Style and Layout blocks, and the green Paint blocks. Many tiny layout blocks in a row, or a layout block with a warning about forced reflow, are the sign of layout thrashing.
  5. Use the CPU throttling option (4x or 6x slowdown) to feel what a slow phone would experience. Your computer is probably much faster than your users’ devices.

The Rendering tab can also show Paint flashing (green flashes where pixels are redrawn), Layout shift regions and an FPS meter.

4. Lighthouse and the Core Web Vitals

Lighthouse (in DevTools) tests a page and gives advice. It reports the Core Web Vitals, three numbers that describe real user experience:

Metric Meaning Short advice
LCP (Largest Contentful Paint) How fast the main content appears Optimise the biggest image or heading, do not lazy load it
INP (Interaction to Next Paint) How quickly the page reacts after a click or key press No long tasks, short event handlers
CLS (Cumulative Layout Shift) How much the page jumps around Set image sizes, reserve space (aspect-ratio)

Benchmark carefully

  • Test with realistic data and amounts. A loop with 10 items says nothing about 10,000.
  • Run each test several times, and compare medians.
  • Change one thing at a time.
  • Test on a slow device or with CPU throttling.
  • Beware of tiny “micro-benchmarks”: the engine may optimise them in a way that does not happen in the real app.

A performance checklist

Instead of… Do this
Animating left, top, width, height Animate transform and opacity
Reading and writing layout in a loop Read all, then write all
Inserting 1000 elements one by one Use a DocumentFragment, or replaceChildren
innerHTML += in a loop Build one string or use a fragment
Many style changes Toggle one class
One listener per item Event delegation
Timers for animation requestAnimationFrame (time-based)
Heavy scroll or resize listeners rafThrottle or throttle, with { passive: true }
Rendering huge lists in one go Chunks, or virtualization
Loading everything on the first visit Lazy load images, features and scripts
Guessing what is slow Measure with performance.now() and DevTools

Real-life use cases

1. A table with 5000 rows

Render it in chunks of 200 to 300 rows per frame, show a progress message, and use event delegation for the row clicks. The user sees data immediately, and the page never freezes.

2. A sticky, shrinking header

Use rafThrottle with a passive scroll listener, and toggle one CSS class. The class change keeps the JavaScript tiny, and CSS does the transition.

3. A count-up statistics section

Use the countUp function with requestAnimationFrame and an easing function. It looks smooth on any screen, because it is based on time.

4. Equal-height product cards

Reset, read all heights, then write the tallest height. (Or, even better, use CSS Grid.)

Use loading="lazy" with a fixed width and height on every image. Only the first screen of photos is downloaded at first.

6. A page with a heavy “Export to PDF” feature

Load the export code with import() only when the user clicks the button, so the first page load stays small and fast.

7. Drag and drop with smooth movement

On mousemove, only store the pointer position. In a requestAnimationFrame callback, move the element with transform. The element follows the pointer at the screen’s own rhythm.

Common mistakes

  • Mixing reads and writes in a loop. Layout thrashing. Read everything first, then write.
  • Animating width, height, top or left when transform and opacity would do.
  • Using setInterval for animation. Use requestAnimationFrame.
  • Moving a fixed number of pixels per frame. Use elapsed time, so that the speed does not depend on the screen.
  • Forgetting to cancel an animation loop that is no longer needed (cancelAnimationFrame).
  • Inserting many elements one at a time into the live page.
  • Using innerHTML += in a loop.
  • Putting heavy work in event handlers for scroll, mousemove or resize without limiting it.
  • Doing 500 ms of work in one function and then wondering why the page freezes. Split it up, or use a worker.
  • Thinking await lets the browser paint. Awaiting a resolved Promise only yields to the microtask queue. Use setTimeout or requestAnimationFrame for that.
  • Lazy loading the most important image at the top of the page. It makes it appear later.
  • Images without width and height. The page jumps when they load.
  • Optimizing without measuring. You may spend hours speeding up something that was never slow.
  • Trusting one measurement, or measuring only on a fast computer.
  • Using will-change everywhere. It uses memory. Apply it only to the few elements that really animate (CSS performance lesson).

Practice

  1. Draw the five steps (JavaScript, Style, Layout, Paint, Composite) and write, next to each, one thing that can trigger it.
  2. Sort these changes into “layout”, “paint only” or “composite only”: width, background-color, transform, opacity, margin, box-shadow, font-size, visibility.
  3. Move a box 300 px to the right with style.left and with style.transform. Which one is cheaper and why?
  4. Create 400 small elements. Write the thrashing loop (read offsetWidth, write style.width) and time it with performance.now().
  5. Rewrite it as read all, then write all, and time it again. Run both five times and compare the medians.
  6. Write equalizeHeights(cards) correctly, with reset, read and write phases.
  7. Insert 2000 li elements one at a time, then with a DocumentFragment, then with replaceChildren. Time all three.
  8. Show why innerHTML += in a loop is a bad idea: add a click listener to the first item, then rebuild the list with += and check if the listener still works.
  9. Replace four style writes with one classList.add call.
  10. Replace 1000 individual click listeners with one delegated listener.
  11. Write an animation loop with requestAnimationFrame that moves a ball with transform. Make it stop at the end.
  12. Rewrite it so that it is time-based (duration and progress from 0 to 1), then add an easing function.
  13. Write animate({ duration, onFrame, easing }) that returns a Promise. Run two animations one after the other with await.
  14. Write countUp(element, target) and use it on a number.
  15. Write rafThrottle(fn) and connect it to the scroll event. Log how many scroll events happen and how many times fn runs.
  16. Render 5000 rows at once, then in chunks of 250 with requestAnimationFrame. Compare how the page feels while it renders (try clicking a button during the render).
  17. Write sumBig(limit) that yields to the main thread every 250,000 steps with setTimeout.
  18. Explain, in your own words, why await Promise.resolve() does not let the browser paint.
  19. Add loading="lazy" plus width and height to a page with many images, and check in the DevTools Network panel which images load first.
  20. Load a heavy feature with import() only when a button is clicked, and confirm in the Network panel that it is not downloaded earlier.
  21. Record a page in the DevTools Performance panel while scrolling. Find a Layout block and a Paint block, and a long task if there is one.
  22. Challenge: write measure(label, fn, runs) that returns the median time, and use it to compare three ways of building a 10,000 item list.
  23. Challenge: build a page with 300 cards and a “Normalize sizes” button. Make the first version thrash, measure it, fix it, and measure again. Take a DevTools recording of both.
  24. Challenge: build a virtual list that renders only the visible rows of a 100,000 item array, and updates the rows during scrolling with rafThrottle.

Recap

  • The browser repeats these steps for each frame: JavaScript, Style, Layout (reflow), Paint (repaint), Composite. At 60 frames per second you have about 16 ms per frame, and everything runs on the main thread.
  • Reflow (geometry changes) is the most expensive. Repaint (look changes) is cheaper. transform and opacity are composite-only and cheapest. Animate those.
  • The browser batches your changes and recalculates the layout lazily. Reading layout properties (offsetWidth, clientHeight, getBoundingClientRect(), getComputedStyle…) after a change forces an immediate layout. Mixing reads and writes in a loop is layout thrashing. Fix it by reading everything first, then writing everything.
  • Batch DOM work: DocumentFragment or replaceChildren, no innerHTML += in loops, one class instead of many style writes, work on a hidden element, cache lookups, and use event delegation.
  • requestAnimationFrame(callback) runs your code just before the next paint, once, with a timestamp. It pauses in background tabs and is cancelled with cancelAnimationFrame. Make animations time-based. Use rafThrottle to run scroll and resize handlers at most once per frame. Prefer CSS animations when a fixed effect is enough.
  • Split long tasks (over about 50 ms) into chunks and yield with requestAnimationFrame or setTimeout, not with a resolved Promise. For truly heavy work, use a Web Worker (next lesson).
  • Lazy load what is not needed yet: loading="lazy" for images and iframes (with width and height), defer and dynamic import() for scripts, lazy values, content-visibility, and virtualization for huge lists. The Intersection Observer lesson comes later.
  • Measure, do not guess: console.time, performance.now() (several runs, use the median), the DevTools Performance panel (long tasks, Layout, Paint, forced reflow), Lighthouse and the Core Web Vitals (LCP, INP, CLS).
  • Next you will learn Web Workers: how to run heavy code on another thread so that the page never freezes.

If you want to revisit the basics, read the CSS performance lesson, the creating and removing elements lesson, the event loop lesson and the debounce and throttle lesson.

Frequently asked questions

What is the difference between reflow and repaint?

A reflow (layout) recalculates the size and position of elements, and it happens when geometry changes, such as width, height or adding elements. A repaint redraws the pixels when only the look changes, such as colour or shadow. Reflow is more expensive, because it can also trigger a repaint and affect many other elements.

What is layout thrashing?

It is what happens when code alternates between changing the DOM (write) and reading a layout value like offsetWidth (read) in a loop. Each read forces the browser to recalculate the layout immediately, so it does the same expensive work again and again. The fix is to do all reads first, then all writes.

Why use requestAnimationFrame instead of setTimeout for animation?

requestAnimationFrame runs your code right before the browser draws a frame, matched to the screen’s refresh rate, so animations are smooth and no frames are wasted. It also pauses in background tabs. A timer fires at its own moment, which can cause uneven motion and wasted work.

Which CSS properties are cheapest to animate?

transform and opacity. They can usually be handled by the compositor without redoing layout or paint. Animating width, height, top or left forces layout on every frame.

How do I know if my code is slow?

Measure it. Use performance.now() or console.time for quick numbers (run several times and take the median), and record a profile in the DevTools Performance panel to see long tasks, layout and paint work. Also test with CPU throttling to simulate a slower device.

Should I add loading="lazy" to every image?

No. Use it for images that are below the first screen. Do not use it on the main image at the top of the page, because lazy loading would delay it. Always set width and height so the page does not jump when images load.

Does using async and await stop my code from freezing the page?

Not by itself. Asynchronous code still runs on the main thread. Awaiting an already finished Promise gives the browser no chance to paint. To avoid freezing, split long work into chunks and yield with setTimeout or requestAnimationFrame, or move the work to a Web Worker.

See also: Debounce and Throttle, Event Loop, CSS Performance and Accessibility, JavaScript Cheat Sheet